📜  Python|交错两个字符串

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

Python|交错两个字符串

有时,在处理字符串时,我们的任务是组合两个字符串,即根据实用性将它们交错。这种类型的实用程序在为游戏编写代码时非常有用。让我们讨论可以执行此操作的某些方式。

方法 #1:使用join() + zip()
可以使用上述功能执行此任务。在此连接函数中,执行在索引处连接每个元素对的两个字符串的任务,而 zip 执行在每个字符串处交织字符的任务。

# Python3 code to demonstrate
# Interleaving two strings
# using join() + zip()
  
# initializing strings 
test_string1 = 'geeksforgeeks'
test_string2 = 'computerfreak'
  
# printing original strings  
print("The original string 1 : " + test_string1)
print("The original string 2 : " + test_string2)
  
# using join() + zip()
# Interleaving two strings
res = "".join(i + j for i, j in zip(test_string1, test_string2))
      
# print result
print("The Interleaved string : " + str(res))
输出 :
The original string 1 : geeksforgeeks
The original string 2 : computerfreak
The Interleaved string : gceoemkpsuftoerrgfereekask

方法 #2:使用zip() + join() + chain.from_iterable()
此任务也可以使用 chain.from_iterable函数来执行。使用这个特定函数的主要优点是它提供了比上述方法更快的速度,比上述方法快大约 3 倍,因为它将字符串转换为可迭代。

# Python3 code to demonstrate
# Interleaving two strings
# using join() + zip() + chain.from_iterable()
from itertools import chain
  
# initializing strings 
test_string1 = 'geeksforgeeks'
test_string2 = 'computerfreak'
  
# printing original strings  
print("The original string 1 : " + test_string1)
print("The original string 2 : " + test_string2)
  
# using join() + zip() + chain.from_iterable()
# Interleaving two strings
res = "".join(list(chain.from_iterable(zip(test_string1, test_string2))))
      
# print result
print("The Interleaved string : " + str(res))
输出 :
The original string 1 : geeksforgeeks
The original string 2 : computerfreak
The Interleaved string : gceoemkpsuftoerrgfereekask