Python有一些内置的函数可以帮助我们将Python对象转换为字符串。其中最常用的是str()函数,它可以将任何Python对象转换为字符串,不管它是什么类型的对象。还有一些其他函数可以帮助我们将Python对象转换为字符串,如repr()函数,它可以将Python对象转换为字符串,并保留原始的数据结构;format()函数,它可以将Python对象转换为格式化的字符串;unicode()函数,它可以将Python对象转换为Unicode字符串;以及bytes()函数,它可以将Python对象转换为字节字符串。
我们介绍str()函数。str()函数可以将任何Python对象转换为字符串,不管它是什么类型的对象。我们可以使用str()函数将数字、列表、元组、字典等对象转换为字符串,例如:
# 将数字转换为字符串
>>> num = 123
>>> str(num)
'123'
# 将列表转换为字符串
>>> lst = [1, 2, 3]
>>> str(lst)
'[1, 2, 3]'
# 将元组转换为字符串
>>> tup = (1, 2, 3)
>>> str(tup)
'(1, 2, 3)'
# 将字典转换为字符串
>>> dic = {'name': 'John', 'age': 20}
>>> str(dic)
"{'name': 'John', 'age': 20}"
我们介绍repr()函数。repr()函数可以将Python对象转换为字符串,并保留原始的数据结构。我们可以使用repr()函数将数字、列表、元组、字典等对象转换为字符串,例如:
# 将数字转换为字符串
>>> num = 123
>>> repr(num)
'123'
# 将列表转换为字符串
>>> lst = [1, 2, 3]
>>> repr(lst)
'[1, 2, 3]'
# 将元组转换为字符串
>>> tup = (1, 2, 3)
>>> repr(tup)
'(1, 2, 3)'
# 将字典转换为字符串
>>> dic = {'name': 'John', 'age': 20}
>>> repr(dic)
"{'name': 'John', 'age': 20}"
再次,我们介绍format()函数。format()函数可以将Python对象转换为格式化的字符串。我们可以使用format()函数将数字、列表、元组、字典等对象转换为字符串,例如:
# 将数字转换为字符串
>>> num = 123
>>> format(num)
'123'
# 将列表转换为字符串
>>> lst = [1, 2, 3]
>>> format(lst)
'[1, 2, 3]'
# 将元组转换为字符串
>>> tup = (1, 2, 3)
>>> format(tup)
'(1, 2, 3)'
# 将字典转换为字符串
>>> dic = {'name': 'John', 'age': 20}
>>> format(dic)
"{'name': 'John', 'age': 20}"
我们还可以使用unicode()函数将Python对象转换为Unicode字符串,以及使用bytes()函数将Python对象转换为字节字符串。例如:
# 将数字转换为Unicode字符串 >>> num = 123 >>> unicode(num) u'123' # 将数字转换为字节字符串 >>> num = 123 >>> bytes(num) b'123'
Python提供了一些内置的函数可以帮助我们将Python对象转换为字符串,包括str()函数