介绍
在大多数其他编程语言中,如果我们将字符串与整数(或任何其他原始数据类型)相连,则该语言将它们转换为字符串,然后将其相连。
然而,在Python中,如果您尝试使用+
运算符连接一个字符串与一个整数,则会出现运行时错误。
例子
让我们看看使用+
运算符连接一个字符串(‘str’)和一个整数(‘int’)的一个例子。
1[label string_concat_int.py]
2current_year_message = 'Year is '
3
4current_year = 2018
5
6print(current_year_message + current_year)
所需的输出是字符串: Year is 2018
. 但是,当我们运行此代码时,我们会收到以下运行时错误:
1Traceback (most recent call last):
2 File "/Users/sammy/Documents/github/journaldev/Python-3/basic_examples/strings/string_concat_int.py", line 5, in <module>
3 print(current_year_message + current_year)
4TypeError: can only concatenate str (not "int") to str
那么在Python中如何连接str
和int
?有各种其他方法来执行此操作。
前提条件
为了完成本教程,您将需要:
- 熟悉安装 Python 3 和熟悉编码在 Python. 如何编码在 Python 3 系列或使用 VS Code for Python)。
本教程是用 Python 3.9.6 测试的。
使用「str()」函数
我們可以將「int」傳送到 `str() 函數它將轉換為「str」:
1print(current_year_message + str(current_year))
current_year
整数作为一个字符串返回: Year is 2018
。
使用%
交互操作器
我们可以通过 printf-style String Formatting将值传递到转换规格:
1print("%s%s" % (current_year_message, current_year))
current_year
整数被插入到一个字符串中:Year is 2018
。
使用「str.format()」函数
我们还可以使用 str.format()
函数来连接字符串和整数。
1print("{}{}".format(current_year_message, current_year))
current_year
整数被强制输入到一个字符串中:Year is 2018
。
使用 f 字符串
如果您正在使用 Python 3.6 或更高版本,您也可以使用 f-strings。
1print(f'{current_year_message}{current_year}')
current_year
整数被插入到一个字符串中:Year is 2018
。
结论
您可以从我们的 GitHub 存储库查看完整的 Python 脚本和更多 Python 示例。