在Python中,`str`是一个内置函数,用于将其他数据类型转换为字符串类型。以下是`str`函数的一些常见用法:
字符串拼接
str1 = "Hello"
str2 = "World"
str3 = str1 + " " + str2 使用加号运算符拼接字符串
print(str3) 输出:Hello World
类型转换
num = 1234
str_num = str(num) 将整数转换为字符串
print(str_num, type(str_num)) 输出:1234
float_num = 3.1415
str_float = str(float_num) 将浮点数转换为字符串
print(str_float, type(str_float)) 输出:3.1415
列表、元组、字典和集合转换为字符串
a_list = [12, -23.1, "Python"]
str_list = str(a_list) 将列表转换为字符串
print(str_list) 输出:'[12, -23.1, 'Python']'
a_tuple = (23, "9we", -8.5)
str_tuple = str(a_tuple) 将元组转换为字符串
print(str_tuple) 输出:'(23, '9we', -8.5)'
a_dictionary = {"Huawei": "China", "Apple": "USA"}
str_dict = str(a_dictionary) 将字典转换为字符串
print(str_dict) 输出:"{'Huawei': 'China', 'Apple': 'USA'}"
a_set = {"China", "Japan", "UK"}
str_set = str(a_set) 将集合转换为字符串
print(str_set) 输出:"{'China', 'Japan', 'UK'}"
自定义对象的字符串表示
class Person:
def __init__(self, name="tom", age=10):
self.name = name
self.age = age
def __str__(self):
return f"Your name is: {self.name}, and you are {self.age} years old."
tom = Person()
print(tom) 输出:Your name is: tom, and you are 10 years old
字符串格式化
name = "Alice"
age = 25
message = f"Hello, {name}! You are {age} years old."
print(message) 输出:Hello, Alice! You are 25 years old
字符串操作
s = "Hello, World!"
print(s) 输出:H
print(s[7:12]) 输出:World!
print(len(s)) 输出:13
以上是`str`函数的一些基本用法,它可以帮助你在Python中方便地处理和操作字符串数据