在 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)
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
运行以上代码,将得到以下结果 -
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))) # 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
广告