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
相关推荐
袁袁袁袁满21 分钟前
基于Python爬虫实战:获取财经股票数据
爬虫·python·ai编程
大模型真好玩30 分钟前
深入浅出LangChain AI Agent智能体开发教程(七)—LangChain多智能体浏览器自动化
人工智能·python·mcp
Kan先生1 小时前
Python调用Openai的Function calling功能—源码
python·openai
码界筑梦坊2 小时前
97-基于Python的大众点评数据分析预测系统
开发语言·python·数据分析
技术老金2 小时前
我为什么又开始手写Agent框架了?从CrewAI和LangGraph的局限谈起
人工智能·python
余子越2 小时前
Python StringIO 和 BytesIO 用法
后端·python
freed_Day2 小时前
人工智能与机器学习基本概念知识入门
开发语言·人工智能·python·机器学习
余子越2 小时前
Python 文件读写详解
后端·python
Waitind_3 小时前
Python数据分析常规步骤整理
开发语言·python·数据分析
这里有鱼汤3 小时前
Python 虚拟环境是什么?它到底是怎么工作的?
后端·python