将一个Python字符串添加到另一个
通过在python中添加字符串,我们只需将它们连接起来即可获得新的字符串。这在诸如文本分析等许多方案中很有用。以下是我们为该任务考虑的两种方法。
使用+=运算符
+运算符可用于字符串,就像数字一样。唯一的区别是,在使用字符串的情况下会发生串联,而不是数字加法。
示例
s1 = "What a beautiful "
s2 = "flower "
print("Given string s1 : " + str(s1))
print("Given string s2 : " + str(s2))
#Using += operator
res1 = s1+s2
print("result after adding one string to another is : ", res1)
# Treating numbers as strings
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()与上述加号运算符类似的方式。我们可以使用此方法连接任意数量的字符串。结果将与加号运算符相同。
示例
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)))
# Treating numbers as strings
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
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短