首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >【Python】字符串 ② ( 字符串拼接 | 字符串与非字符串不能直接拼接 | TypeError: can only concatenate str (not “int“) to str )

【Python】字符串 ② ( 字符串拼接 | 字符串与非字符串不能直接拼接 | TypeError: can only concatenate str (not “int“) to str )

作者头像
韩曙亮
发布于 2023-04-07 15:50:14
发布于 2023-04-07 15:50:14
7570
举报

文章目录

一、Python 字符串拼接


Python 字符串拼接 可以通过 + 运算符 进行 ;

代码语言:javascript
复制
"Tom" + " 19"

拼接后的结果是 "Tom 19" ;

上面是 字面量 与 字面量 进行拼接 ;

字面量 与 变量 , 变量 与 变量 之间 , 也可以进行拼接 ;

  • 字面量 与 变量拼接示例 : 字符串 字面量 可以 与 字符串变量 进行拼接 ;
代码语言:javascript
复制
	# 字面量 与 变量 拼接
	name = "Tom "
	print(name + "19")
  • 变量 与 变量 拼接示例 : 字符串 变量 可以 与 字符串变量 进行拼接 ;
代码语言:javascript
复制
	# 变量 与 变量 拼接
	name = "Tom "
	age = "19"
	print(name + age)

完整代码示例 : 字符串的变量与字面量之间可以进行任意直接拼接操作 ;

代码语言:javascript
复制
# 字面量 与 字面量 拼接
print("Tom" + " 19")

# 字面量 与 变量 拼接
name = "Tom "
print(name + "19")

# 变量 与 变量 拼接
name = "Tom "
age = "19"
print(name + age)

执行结果 :

代码语言:javascript
复制
Tom 19
Tom 19
Tom 19

二、字符串与非字符串不能直接拼接


字符串不能与非字符串进行拼接 , 如下代码 , 字符串与数字进行拼接 ;

代码语言:javascript
复制
# 字符串变量 与 数字拼接
name = "Tom"
print(name + 18)

上述代码执行会报错 : TypeError: can only concatenate str (not “int”) to str ;

代码语言:javascript
复制
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
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-04-06,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • 文章目录
  • 一、Python 字符串拼接
  • 二、字符串与非字符串不能直接拼接
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档