将一个 Python 字符串添加到另一个字符串

pythonserver side programmingprogramming更新于 2025/7/3 15:40:17

通过在 Python 中添加字符串,我们只需将它们连接起来即可获得一个新字符串。这在许多场景中都很有用,例如文本分析等。以下是我们为这项任务考虑的两种方法。

使用 += 运算符

+ 运算符可以像用于数字一样用于字符串。唯一的区别是,在字符串的情况下,会发生连接而不是数字加法。

示例

s1 = "多么美丽"
s2 = "花"

print("Given string s1 : " + str(s1))
print("Given string s2 : " + str(s2))
#使用 += 运算符
res1 = s1+s2
print("result after adding one string to another is : ", res1)

# 将数字视为字符串
s3 = '54'
s4 = '02'
print("Given string s1 : " + str(s3))
print("Given string s2 : " + str(s4))
res2 = s3+s4
print("result after adding one string to another is : ", res2)

输出

运行上述代码得到以下结果 −

Given string s1 : What a beautiful
Given string s2 : flower
result after adding one string to another is : What a beautiful flower
Given string s1 : 54
Given string s2 : 02
result after adding one string to another is : 5402

使用 join

我们可以以与上面的加法运算符类似的方式使用 join()。我们可以使用此方法连接任意数量的字符串。结果将与加法运算符相同。

示例

s1 = "What a beautiful "
s2 = "flower "

print("Given string s1 : " + str(s1))
print("Given string s2 : " + str(s2))
print("result after adding one string to another is : "," ".join((s1,s2)))

# 将数字视为字符串
s3 = '54'
s4 = '02'
print("Given string s1 : " + str(s3))
print("Given string s2 : " + str(s4))
print("result after adding one string to another is : ","".join((s3,s4)))

输出

运行上述代码得到以下结果 −

Given string s1 : What a beautiful
Given string s2 : flower
result after adding one string to another is : What a beautiful flower
Given string s1 : 54
Given string s2 : 02
result after adding one string to another is : 5402

相关文章


有用资源