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
相关推荐
love530love35 分钟前
【笔记】记一次PyCharm的问题反馈
ide·人工智能·windows·笔记·python·pycharm
梦醒沉醉36 分钟前
MCP(一)——QuickStart
python·mcp
照物华38 分钟前
httpx[http2] 和 httpx 的核心区别及使用场景如下
python·httpx
山海不说话1 小时前
PyGame游戏开发(入门知识+组件拆分+历史存档/回放+人机策略)
开发语言·python·pygame
胡耀超1 小时前
探讨零知识证明的数学原理与应用
python·web安全·区块链·密码学·数据安全·零知识证明
不许哈哈哈2 小时前
自动化点击工具
运维·python·自动化
满怀10153 小时前
【Flask全栈开发指南】从零构建企业级Web应用
前端·python·flask·后端开发·全栈开发
PWRJOY3 小时前
Flask-SQLAlchemy_数据库配置
数据库·python·flask
mahuifa3 小时前
Qt图表绘制(QtCharts)- 性能优化(13)
python·qt·pyside6·开发经验·qtchart
Bugabooo3 小时前
python打卡DAY22
开发语言·python