Python: encuentra palabras con letras y números

A veces, mientras trabajamos con strings de Python, podemos tener problemas en los que necesitamos extraer ciertas palabras que contienen tanto números como alfabetos. Este tipo de problema puede ocurrir en muchos dominios, como la programación escolar y el desarrollo web. Analicemos ciertas formas en que se puede realizar esta tarea.

Método #1: Usarany() + isdigit() + isalpha()
La combinación de las funcionalidades anteriores se puede usar para realizar esta tarea. En esto, iteramos todas las palabras y verificamos la combinación requerida usando isdigit()e isalpha().

# Python3 code to demonstrate working of 
# Words with both alphabets and numbers
# Using isdigit() + isalpha() + any()
  
# initializing string
test_str = 'geeksfor23geeks is best45 for gee34ks and cs'
  
# printing original string
print("The original string is : " + test_str)
  
# Words with both alphabets and numbers
# Using isdigit() + isalpha() + any()
res = []
temp = test_str.split()
for idx in temp:
    if any(chr.isalpha() for chr in idx) and any(chr.isdigit() for chr in idx):
        res.append(idx)
          
# printing result 
print("Words with alphabets and numbers : " + str(res)) 
Producción :

La string original es: geeksfor23geeks es best45 para gee34ks y cs
Palabras con alfabetos y números: [‘geeksfor23geeks’, ‘best45’, ‘gee34ks’]

Método #2: Uso de expresiones regulares
Esta es otra forma en la que podemos realizar esta tarea. En esto, alimentamos la string a findall()y extraemos el resultado requerido. Devuelve strings hasta los números solamente.

# Python3 code to demonstrate working of 
# Words with both alphabets and numbers
# Using regex
import re
  
# initializing string
test_str = 'geeksfor23geeks is best45 for gee34ks and cs'
  
# printing original string
print("The original string is : " + test_str)
  
# Words with both alphabets and numbers
# Using regex
res = re.findall(r'(?:\d+[a-zA-Z]+|[a-zA-Z]+\d+)', test_str)
          
# printing result 
print("Words with alphabets and numbers : " + str(res)) 
Producción :

La string original es: geeksfor23geeks es best45 para gee34ks y cs
Palabras con alfabetos y números: [‘geeksfor23’, ‘best45’, ‘gee34’]

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 *