在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