本文介绍了如何将Python整数转换为字符串。
Python有几种内置数据类型。有时,在编写Python代码时,您可能需要将一种数据类型转换为另一种数据类型。例如,连接一个字符串和整数,首先,您需要将整数转换为字符串。
Pythonstr()函数
在Python中,我们可以使用内置str()函数将整数和其他数据类型转换为字符串。
该str()函数返回给定对象的字符串版本。它采取以下形式:
class str(object=”)
class str(object=b”, encoding=’utf-8′, errors=’strict’)
object -要转换为字符串的对象。
该函数接受三个参数,但是通常,当将整数转换为字符串时,仅将一个参数(object)传递给该函数。
将Python整数转换为字符串
要将整数23转换为字符串版本,只需将数字传递给str()函数:
str(23)
type(days)
输出:
’23’
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 “”, line 1, in
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.
还有其他方式来连接字符串和数字。
内置字符串类提供了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()函数将整数转换为字符串。