使用+=赋值运算符拼接字符串报错:为何被识别为元组?
为什么使用+=拼接多个字符串时会被识别为元组?
你的代码:
MyStr = "" MyStr += "Hello ","Word"
运行时触发错误:
Exception has occurred: TypeError
can only concatenate str (not "tuple") to str
原因解析
在Python里,逗号分隔的多个值会被自动打包成元组,所以"Hello ","Word"本质上是创建了一个元组("Hello ", "Word"),而非两个独立的字符串。而字符串的+=运算符要求右侧必须是单个字符串类型,当你把元组传过去时,Python无法把字符串和元组拼接,就抛出了类型错误。
正确的拼接方式
如果要一次性拼接多个字符串,试试这些写法:
- 先把多个字符串合并成单个再用
+=:
MyStr = "" MyStr += "Hello " + "Word"
- 用
str.join()(拼接大量字符串时更高效):
MyStr = "" MyStr += "".join(["Hello ", "Word"])
- 利用Python字符串字面量的自动拼接(注意不要加逗号):
MyStr = "" MyStr += "Hello " "Word"
内容的提问来源于stack exchange,提问作者GamerDan123
相关产品推荐
相关产品推荐

