Python字符串与整数拼接:实用技巧与常见陷阱
简介
Python支持使用+
运算符进行字符串拼接。在大多数其他编程语言中,如果我们将字符串与整数(或其他原始数据类型)连接起来,语言会自动将其转换为字符串然后拼接。
然而,在Python中,如果你试图使用+
运算符将字符串与整数连接起来,你将会得到一个运行时错误。
示例
让我们看一个使用+
运算符连接字符串(str)和整数(int)的例子。
字符串连接整数.py
current_year_message = 'Year is '
current_year = 2018
print(current_year_message + current_year)
期望的输出是字符串:年份为2018
。然而,当我们运行这段代码时,会出现以下运行时错误。
Traceback (most recent call last):
File "/Users/sammy/Documents/github/scdev/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中,你如何将字符串和整数连接起来?这个操作有其他多种方法可以实现。
先决条件
为了完成本教程,你将需要:
- 熟悉Python 3的安装,并熟悉Python编程。可以参考《Python 3编程系列》或使用VS Code进行Python开发。
本教程是使用Python 3.9.6进行测试的。
使用str()
函数
我们可以将一个整数传递给str()
函数,它将被转换为字符串。
print(current_year_message + str(current_year))
返回当前年份整数作为字符串:年份为2018年
。
使用%
插值运算符
我们可以使用类似C语言printf
的字符串格式化方式来向转换规范传递值。
print("%s%s" % (current_year_message, current_year))
当前年份整数被插入字符串中:年份为2018年
。
使用str.format()
函数
我们还可以使用str.format()
函数将字符串和整数拼接在一起。
print("{}{}".format(current_year_message, current_year))
当前年份整数被强制转换为字符串:年份是2018
。
使用f-strings
如果你正在使用Python 3.6或更高版本,你也可以使用f-字符串。
print(f'{current_year_message}{current_year}')
当前年份整数被转换为字符串:年份为2018年
。
结论
你可以从我们的GitHub代码库中查看完整的Python脚本和更多的Python例子。