文章目录
- 一、Python 字符串拼接
- 二、字符串与非字符串不能直接拼接
一、Python 字符串拼接
Python 字符串拼接 可以通过 +
运算符 进行 ;
"Tom" + " 19"
拼接后的结果是 "Tom 19"
;
上面是 字面量 与 字面量 进行拼接 ;
字面量 与 变量 , 变量 与 变量 之间 , 也可以进行拼接 ;
- 字面量 与 变量拼接示例 : 字符串 字面量 可以 与 字符串变量 进行拼接 ;
# 字面量 与 变量 拼接
name = "Tom "
print(name + "19")
- 变量 与 变量 拼接示例 : 字符串 变量 可以 与 字符串变量 进行拼接 ;
# 变量 与 变量 拼接
name = "Tom "
age = "19"
print(name + age)
完整代码示例 : 字符串的变量与字面量之间可以进行任意直接拼接操作 ;
# 字面量 与 字面量 拼接
print("Tom" + " 19")
# 字面量 与 变量 拼接
name = "Tom "
print(name + "19")
# 变量 与 变量 拼接
name = "Tom "
age = "19"
print(name + age)
执行结果 :
Tom 19
Tom 19
Tom 19
二、字符串与非字符串不能直接拼接
字符串不能与非字符串进行拼接 , 如下代码 , 字符串与数字进行拼接 ;
# 字符串变量 与 数字拼接
name = "Tom"
print(name + 18)
上述代码执行会报错 : TypeError: can only concatenate str (not “int”) to str ;
Traceback (most recent call last):
File "Y:\002_WorkSpace\PycharmProjects\HelloPython\hello.py", line 3, in <module>
print(name + 18)
TypeError: can only concatenate str (not "int") to str
Process finished with exit code 1