📜  Python - 通过多个分隔符连接字符串

📅  最后修改于: 2022-05-13 01:55:25.143000             🧑  作者: Mango

Python - 通过多个分隔符连接字符串

给定两个字符串,任务是编写一个Python程序,通过分隔符列表中的每个分隔符连接它们。

方法 1:使用列表理解

在这里,我们使用列表理解中的循环遍历列表中的所有分隔符,并且 +运算符执行连接任务。

例子:

Python3
# initializing strings
test_str1 = 'Geeksforgeeks'
test_str2 = "Best"
  
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
  
# initializing join list
join_list = ["+", "*", "-", "$", ",", "@"]
  
# + operator used for concatenations
res = [test_str1 + delim + test_str2 for delim in join_list]
  
# printing result
print("All delimiters concatenations : " + str(res))


Python3
# initializing strings
test_str1 = 'Geeksforgeeks'
test_str2 = "Best"
  
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
  
# initializing join list
join_list = ["+", "*", "-", "$", ",", "@"]
  
# join() operator used for concatenations
res = [delim.join([test_str1, test_str2]) for delim in join_list]
  
# printing result
print("All delimiters concatenations : " + str(res))


输出:

方法 2:使用join()列表推导

与上述方法类似,不同之处在于使用 join() 执行加入任务,而不是 +运算符。

例子:

蟒蛇3

# initializing strings
test_str1 = 'Geeksforgeeks'
test_str2 = "Best"
  
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
  
# initializing join list
join_list = ["+", "*", "-", "$", ",", "@"]
  
# join() operator used for concatenations
res = [delim.join([test_str1, test_str2]) for delim in join_list]
  
# printing result
print("All delimiters concatenations : " + str(res))

输出: