Python 有多种内置数据类型。有时,在编写 Python 代码时,您可能需要将一种数据类型转换为另一种数据类型。例如,连接一个字符串和整数,首先,您需要将整数转换为字符串。
本文介绍如何将 Python 整数转换为字符串。
Python str()
功能#
在Python中,我们可以使用内置的函数将整数和其他数据类型转换为字符串str()
功能。
The str()
函数返回给定对象的字符串版本。它有以下几种形式:
class str(object='')
class str(object=b'', encoding='utf-8', errors='strict')
该函数接受三个参数,但通常,将整数转换为字符串时,您只传递一个参数(object
) 到函数。
将 Python 整数转换为字符串#
要将整数 23 转换为字符串版本,只需将数字传递到str()
功能:
'23'
<class 'str'>
23 左右的引号表示该数字不是整数,而是字符串类型的对象。另外,type()
函数显示该对象是一个字符串。
在 Python 中,字符串是使用单个 ('
), 双倍的 ("
),或三引号 ("""
).
连接字符串和整数#
让我们尝试使用连接字符串和整数+
运算符并打印结果:
number = 6
lang = "Python"
quote = "There are " + number + " relational operators in " + lang + "."
print(quote)
Python 会抛出一个TypeError
异常错误,因为它无法连接字符串和整数:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
要将整数转换为字符串,请将整数传递给str()
功能:
number = 6
lang = "Python"
quote = "There are " + str(number) + " relational operators in " + lang + "."
print(quote)
现在,当您运行代码时,它将成功执行:
There are 6 relational operators in Python.
还有其他方法可以连接字符串和数字。
内置的 string 类提供了format()
使用任意一组位置和关键字参数格式化给定字符串的方法:
number = 6
lang = "Python"
quote = "There are {} relational operators in {}.".format(number, lang)
print(quote)
There are 6 relational operators in Python.
在 Python 3.6 及更高版本中,您可以使用 f 字符串,它们是以“f”为前缀的文字字符串,其中包含大括号内的表达式:
number = 6
lang = "Python"
quote = f"There are {number} relational operators in {lang}."
print(quote)
There are 6 relational operators in Python.
最后,您可以使用旧的 % 格式:
number = 6
lang = "Python"
quote = "There are %s relational operators in %s." % (number, lang)
print(quote)
There are 6 relational operators in Python.
结论#
在 Python 中,您可以使用以下命令将整数转换为字符串:str()
功能。
如果您有任何问题或反馈,请随时发表评论。