str()
函数用于将指定的值转换为字符串。它可以将数字、列表、元组、字典等不同类型的数据转换为字符串类型。例如:
num = 123
str_num = str(num)
print(str_num) # 输出:'123'
my_list = [1, 2, 3]
str_list = str(my_list)
print(str_list) # 输出:'[1, 2, 3]'
my_dict = {'key1': 'value1', 'key2': 'value2'}
str_dict = str(my_dict)
print(str_dict) # 输出:{'key1': 'value1', 'key2': 'value2'}
str()
函数还可以用于将特殊字符转义为字符串表示。例如:
special_char = '\n' # 换行符
str_special_char = str(special_char)
print(str_special_char) # 输出:'\n'