Python | Intercalar dos strings

A veces, mientras trabajamos con strings, tenemos la tarea de combinar dos strings, es decir, intercalarlas según la utilidad. Este tipo de utilidad es principalmente útil al escribir códigos para juegos. Analicemos ciertas formas en que esto se puede realizar.

Método #1: Usojoin() + zip()
Esta tarea se puede realizar usando las funciones anteriores. En esta función de unión realiza la tarea de unir dos strings de cada par de elementos en un índice y zip realiza la tarea de intercalar caracteres en cada string.

# 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))
Producción :

 
The original string 1 : geeksforgeeks
The original string 2 : computerfreak
The Interleaved string : gceoemkpsuftoerrgfereekask

Método #2: Usarzip() + join() + chain.from_iterable()
Esta tarea también se puede realizar usando la función chain.from_iterable. La principal ventaja de usar esta función en particular es que ofrece más velocidad que el método anterior, aproximadamente 3 veces más rápido que el método anterior, ya que convierte la string en iterable.

# 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))
Producción :

 
The original string 1 : geeksforgeeks
The original string 2 : computerfreak
The Interleaved string : gceoemkpsuftoerrgfereekask

Publicación traducida automáticamente

Artículo escrito por manjeet_04 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *