Python 字符串常见的9种拼接方式

在python开发中,字符串的拼接,是常见的操作,实现的方法也是多种多样,记录如下:

1、 加号 + 运算符拼接:

python 复制代码
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)  
# 输出: Hello World

2、在 print 函数中,使用逗号 , 拼接:

python 复制代码
str1 = "Hello"
str2 = "World"
print(str1, str2)  
# 输出: Hello World

3、使用 字符串.join 函数拼接:

python 复制代码
str1 = "Hello"
str2 = "World"
result = " ".join([str1, str2])
print(result)  
# 输出: Hello World

4、使用 % 格式化字符串拼接:

python 复制代码
str1 = "Hello"
str2 = "World"
result = "%s %s" % (str1, str2)
print(result)  # 输出: Hello World

5、使用 字符串.format 方法拼接:

python 复制代码
str1 = "Hello"
str2 = "World"
result = "{} {}".format(str1, str2)
print(result)  
# 输出: Hello World

6、使用 f(格式化字符串字面量)拼接:

python 复制代码
str1 = "Hello"
str2 = "World"
result = f"{str1} {str2}"
print(result)  
# 输出: Hello World

7、使用 StringIO 模块拼接:

python 复制代码
from io import StringIO 
str1 = "Hello"
str2 = "World"
buffer = StringIO()
buffer.write(str1)
buffer.write(" ")
buffer.write(str2)
result = buffer.getvalue()
print(result)  
# 输出: Hello World

8、使用 += 运算符拼接:

python 复制代码
str1 = "Hello"
str2 = "World"
str1 += " " + str2
print(str1)  
# 输出: Hello World

9、使用列表中的append方法拼接:

python 复制代码
str1 = "Hello"
str2 = "World"
result = []
result.append(str1)
result.append(" ")
result.append(str2)
result = "".join(result)
print(result)  
# 输出: Hello World
相关推荐
第一程序员1 小时前
Python数据结构与算法:非科班转码者的学习指南
python·github
weixin_586061461 小时前
如何用 event.composedPath 获取事件触发经过的所有节点
jvm·数据库·python
weixin_408717772 小时前
如何用 Iterator.from 将类数组转化为具备现代方法的迭代器
jvm·数据库·python
Full Stack Developme2 小时前
MyBatis-Plus 流式查询教程
前端·python·mybatis
才兄说2 小时前
机器人二次开发机器狗巡检?定位精度±2cm
python
2301_782659182 小时前
SQL视图能否用于数据仓库模型_雪花模型与视图构建
jvm·数据库·python
m0_377618232 小时前
CSS如何让文字超出两行显示省略号_使用line-clamp属性限制
jvm·数据库·python
m0_743623922 小时前
HTML5中LocalStorage存储用户自定义快捷键配置
jvm·数据库·python
2301_773553622 小时前
HTML5中SharedWorker生命周期与浏览器进程关闭的关系
jvm·数据库·python
m0_640309302 小时前
mysql flush privileges有什么作用_mysql权限生效机制解析
jvm·数据库·python