介绍
Python支持使用+
运算符进行字符串连接。在大多数其他编程语言中,如果我们将字符串与整数(或任何其他原始数据类型)连接起来,语言会负责将它们转换为字符串,然后进行连接。
然而,在Python中,如果尝试使用+
运算符将字符串与整数连接,将会导致运行时错误。
示例
让我们看一个使用+
运算符连接字符串(str
)和整数(int
)的示例。
string_concat_int.py
current_year_message = 'Year is '
current_year = 2018
print(current_year_message + current_year)
期望的输出是字符串:Year is 2018
。然而,当运行此代码时,我们会得到以下运行时错误:
Traceback (most recent call last):
File "/Users/sammy/Documents/github/journaldev/Python-3/basic_examples/strings/string_concat_int.py", line 5, in <module>
print(current_year_message + current_year)
TypeError: can only concatenate str (not "int") to str
那么在Python中如何连接str
和int
呢?有各种其他方法执行此操作。
先决条件
为了完成本教程,您将需要:
- 熟悉安装Python 3,并熟悉在Python中编码。如何在Python 3系列中编码 或使用VS Code进行Python。
本教程已使用Python 3.9.6进行测试。
使用str()
函数
我们可以将一个int
传递给str()
函数它将被转换为一个str
:
print(current_year_message + str(current_year))
整数current_year
被返回为字符串:Year is 2018
。
使用%
插值运算符
我们可以使用printf风格的字符串格式化将值传递给转换规范:
print("%s%s" % (current_year_message, current_year))
整数current_year
被插值为字符串:Year is 2018
。
使用str.format()
函数
我们还可以使用str.format()
函数进行字符串和整数的拼接。
print("{}{}".format(current_year_message, current_year))
整数current_year
被强制转换为字符串:Year is 2018
。
使用f-strings
如果你使用的是Python 3.6或更高版本,你也可以使用f-strings。
print(f'{current_year_message}{current_year}')
整数current_year
被插值为字符串:Year is 2018
。
结论
你可以从我们的GitHub仓库查看完整的Python脚本和更多Python示例。
Source:
https://www.digitalocean.com/community/tutorials/python-concatenate-string-and-int