Python 如何实现字符串连接而不使用’+’运算符
在本文中,我们将探讨在Python中如何在不使用加号运算符的情况下进行字符串连接。
第一种技巧是利用字符串内置库的 join() 方法。通过这种方法可以使用分隔符混合字符串。该方法输出一个字符串序列。
Python的 join() 方法提供了将已由字符串运算符分隔开的可迭代组件组合的能力。要使用内置的Python join函数返回一个字符串连接了序列项的迭代器字符串,可以使用它。
示例1
在下面给出的示例中,我们输入2个字符串,并使用 join() 方法使用空格进行连接。
str1 = "Welcome"
str2 = "Tutorialspoint"
print("The first string is")
print(str1)
print("The second string is")
print(str2)
concat = " ".join([str1,str2])
print("The concatenated string is")
print(concat)
输出
以上示例的输出如下所示:
The first string is
Welcome
The second string is
Tutorialspoint
The concatenated string is
Welcome Tutorialspoint
示例2
在下面给出的程序中,我们使用相同的程序,但是我们将输入的字符串与空格连接在一起 −
str1 = "Welcome"
str2 = "Tutorialspoint"
print("The first string is")
print(str1)
print("The second string is")
print(str2)
concat = "".join([str1,str2])
print("The concatenated string is")
print(concat)
输出
上面示例的输出如下 –
The first string is
Welcome
The second string is
Tutorialspoint
The concatenated string is
WelcomeTutorialspoint
示例3
在下面给出的示例中,我们使用‘ , ’操作符进行拼接的方式与上述示例相同。
str1 = "Welcome"
str2 = "Tutorialspoint"
print("The first string is")
print(str1)
print("The second string is")
print(str2)
concat = ",".join([str1,str2])
print("The concatenated string is")
print(concat)
输出
上述示例的输出如下所示:
The first string is
Welcome
The second string is
Tutorialspoint
The concatenated string is
Welcome,Tutorialspoint
使用filter()方法
第二种技术是使用字符串库中的format()函数,这是一种固有的方法。它通常用于打印语句中包含变量。为了表示某个变量存在,我们将使用双引号中的花括号,然后在format()函数中指定变量名。 **函数。
示例
在下面的示例中,我们以2个字符串作为输入,使用filter()操作进行拼接。
str1 = "Welcome"
str2 = "Tutorialspoint"
print("The first string is")
print(str1)
print("The second string is")
print(str2)
concat = "{} {}".format(str1, str2)
print("The concatenated string is")
print(concat)
输出
上述示例的输出如下所示:
The first string is
Welcome
The second string is
Tutorialspoint
The concatenated string is
Welcome Tutorialspoint