将一个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