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'