在Linux中可使用str()函数将Python整数转换为字符串

2022年 12月 21日 13.1k 0

本文所使用的环境是Linux操作系统,在系统中使用Python str()函数可将Python整数转换为字符串,另外,本文还讲解连接字符串和整数的方法。当前Python有几种内置数据类型,有时,在编写Python代码时,您可能需要将一种数据类型转换为另一种数据类型,例如,连接一个字符串和整数,首先您需要将整数转换为字符串,以下就来一起操作。
转换方法
Python str()函数
在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'<class 'str'>
23周围的引号表示数字不是整数,而是字符串类型的对象,同样,type()函数表明该对象是一个字符串。
注:在Python中,使用单引号('),双引号(")或三引号(""")声明字符串。
连接字符串和整数
让我们尝试使用+运算符将字符串和整数连接起来并打印结果:
number = 6lang = "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 = 6lang = "Python"quote = "There are " + str(number) + " relATIonal operators in " + lang + "."print(quote)
现在,当您运行代码时,它将成功执行:
There are 6 relational operators in Python.
还有其他方式来连接字符串和数字。
内置的字符串类提供了format()方法,该方法使用任意一组位置和关键字参数来格式化给定的字符串:
number = 6lang = "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 = 6lang = "Python"quote = f"There are {number} relational operators in {lang}."print(quote)
返回:
There are 6 relational operators in Python.
最后,您可以使用旧的%-格式:
number = 6lang = "Python"quote = "There are %s relational operators in %s." % (number, lang)print(quote)
返回:
There are 6 relational operators in Python.
如果要在Python中将整数转换为字符串,使用str()函数就可以达到目的了。

相关文章

服务器端口转发,带你了解服务器端口转发
服务器开放端口,服务器开放端口的步骤
产品推荐:7月受欢迎AI容器镜像来了,有Qwen系列大模型镜像
如何使用 WinGet 下载 Microsoft Store 应用
百度搜索:蓝易云 – 熟悉ubuntu apt-get命令详解
百度搜索:蓝易云 – 域名解析成功但ping不通解决方案

发布评论