python 如何合并字符

原创
ithorizon 7个月前 (09-29) 阅读数 36 #Python

合并字符串在 Python 中有多种方式,下面是一些常用的方法:

1、使用加号(+):

str1 = "Hello, "
str2 = "World!"
result = str1 + str2
print(result)  # 输出:Hello, World!

2、使用字符串的join() 方法:

str1 = "Hello, "
str2 = "World!"
result = str1 + str2
print(result)  # 输出:Hello, World!

3、使用字符串的format() 方法:

str1 = "Hello, {}"
str2 = "World!"
result = str1.format(str2)
print(result)  # 输出:Hello, World!

4、使用 f-string(在 Python 3.6 及以上版本可用):

str1 = "Hello, "
str2 = "World!"
result = f"{str1}{str2}"
print(result)  # 输出:Hello, World!

方法都可以实现字符串的合并,具体使用哪种方法取决于你的需求和编程习惯。



热门