字符串连接与整数和浮动一样,Python中的字符串可以使用一个+号连接起来连接字符串时,不管他们是否已经与单或双引号了。
>>> "王者" + '吃鸡''王者吃鸡'
>>> print("第一个字符串" + ", " + "第二个字符串")
第一个字符串, 第二个字符串
字符串与其它类型连接即使字符串包含数字,它们仍然是作为字符串而不是数字添加的。在数字中添加一个字符串会产生一个错误,因为尽管它们看起来很相似,但它们是两个不同的概念。
>>> "2" + "2"'22'
>>> 1 + '2' + 3 + '4'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
输出反馈(最近的一次错误):
文件”<控制台>“,第1行,在<模块>
类型错误:不支持 ’整数‘和’字符串‘两种类型运算操作
traceback 输出反馈
line1 第一行
typeError 类型错误
int 整数
str 字符串
思考以下代码哪行出现错误
- "4"+"ww"+6/12
- 1+2
- "love"+'520'
- "40"+"324"
字符串操作字符串也可以用整数相乘。这会让字符串重复。字符串和整数的顺序无关紧要,字符串不能由其他字符串相乘。字符串也不能用浮点数相乘,即使浮点数是整数。
>>> print("spam" * 3)
spamspamspam
>>> 4 * '2'
'2222'
>>> '17' * '87'
TypeError: can't multiply sequence by non-int of type 'str'# 类型错误:字符串不能和非整数类型相乘
>>> 'pythonisfun' * 7.0
TypeError: can't multiply sequence by non-int of type 'float'# 类型错误:浮点数不能和非整数类型相乘
思考:
>>> print(3 * '7')
上面输出结果是什么