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
相关推荐
之歆11 分钟前
Python-封装和解构-set及操作-字典及操作-解析式生成器-内建函数迭代器-学习笔记
笔记·python·学习
天天爱吃肉82181 小时前
ZigBee通信技术全解析:从协议栈到底层实现,全方位解读物联网核心无线技术
python·嵌入式硬件·物联网·servlet
Allen_LVyingbo2 小时前
Python常用医疗AI库以及案例解析(2025年版、上)
开发语言·人工智能·python·学习·健康医疗
智能砖头2 小时前
LangChain 与 LlamaIndex 深度对比与选型指南
人工智能·python
风逸hhh3 小时前
python打卡day58@浙大疏锦行
开发语言·python
烛阴4 小时前
一文搞懂 Python 闭包:让你的代码瞬间“高级”起来!
前端·python
JosieBook4 小时前
【Java编程动手学】Java中的数组与集合
java·开发语言·python
Gyoku Mint5 小时前
深度学习×第4卷:Pytorch实战——她第一次用张量去拟合你的轨迹
人工智能·pytorch·python·深度学习·神经网络·算法·聚类
郭庆汝11 小时前
pytorch、torchvision与python版本对应关系
人工智能·pytorch·python
思则变14 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest