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
相关推荐
何以解忧,唯有..3 小时前
Python 元组(tuple)详解:使用、遍历与排序
开发语言·python
KANGBboy3 小时前
Python eval安全隐患
开发语言·python
evans在进步4 小时前
LeetCode 394:字符串解码——Java 单栈模拟与嵌套解析详解
java·python·leetcode
淼澄研学4 小时前
Python结合大模型挖掘搜题长尾关键词实操指南
开发语言·python
中科高级技工学校6 小时前
乌鲁木齐美术艺考技校实践分享
人工智能·python
CodeBlog-star6 小时前
LLM能力与边界:多模态、幻觉、上下文窗口及开源模型对比
人工智能·python·开源·llm
COOLMO研究AI6 小时前
Python 如何实现 AI API 的动态路由与多通道负载均衡:多账号与多供应商的高可用调度
人工智能·python·负载均衡
菜冻鱼7 小时前
Python-sklearn-降维
开发语言·人工智能·python·机器学习·支持向量机·sklearn
OptimizationMaster7 小时前
Python自动重启中国移动光猫(ZXHN G7611V2)
python·自动化工具·重启中国移动光猫
hhzz8 小时前
Tiger AI 平台「手势识别」功能全解析:从数字手势 0–9,到中国手语字母,再到本地视频批量识别——一条链路,三种输入,双模型可同开;双手比划,机器秒懂
人工智能·python·深度学习·aigc·音视频