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
相关推荐
徐凤年lll1 小时前
python 初学2
开发语言·python
坚持就完事了2 小时前
解析数据练习(小项目)
python
周周记笔记2 小时前
Pycharm详解:高效Python开发的首选IDE
ide·python·pycharm
香辣西红柿炒蛋2 小时前
Python企业编码规范
python
Anson Jiang3 小时前
PyTorch轻松实现CV模型:零基础到实战
pytorch·python·django·flask·python开发
风雨同舟的代码笔记3 小时前
5.Python函数与模块化工程实战:构建高复用代码体系
python
我的xiaodoujiao4 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 22--数据驱动--参数化处理 Json 文件
python·学习·测试工具·pytest
别慌,让我先缓缓4 小时前
PyModbus 从入门到精通教程
python
景彡先生4 小时前
Python Flask详解:从入门到实战,轻量级Web框架的魅力
前端·python·flask
JJJJ_iii4 小时前
【机器学习12】无监督学习:K-均值聚类与异常检测
人工智能·笔记·python·学习·机器学习·均值算法·聚类