Dada una string, nuestra tarea es escribir un programa en Python para comprobar si la string contiene tanto números como letras, pero no signos de puntuación.
Ejemplos:
Input : test_str = 'Geeks4Geeks' Output : True Explanation : Contains both number and alphabets. Input : test_str = 'GeeksforGeeks' Output : False Explanation : Doesn't contain number.
Método #1: Usando isalpha() + isdigit() + any() + all() + isalnum()
En esto, verificamos todos los dígitos que contienen una combinación de letras y números usando all(), isalpha() e isdigit(). Any() e isalnum() se utilizan para filtrar la posibilidad de puntuaciones.
Python3
# Python3 code to demonstrate working of # Test if string contains both Numbers and Alphabets only # Using isalpha() + isdigit() + any() + all() + isalnum() # initializing string test_str = 'Geeks4Geeks' # printing original string print("The original string is : " + str(test_str)) # conditional combination for getting result. res = not ((all(idx.isdigit() for idx in test_str) or (all(idx.isalpha() for idx in test_str)) or (any(not idx.isalnum() for idx in test_str)))) # printing result print("Does string contain both numbers and alphabets only? : " + str(res))
Producción
The original string is : Geeks4Geeks Does string contain both numbers and alphabets only? : True
Método #2: Usar expresiones regulares
El uso de expresiones regulares es una de las formas en que se puede resolver este problema.
Python3
# Python3 code to demonstrate working of # Test if string contains both Numbers and Alphabets only # Using regex import re # initializing string test_str = 'Geeks4Geeks' # printing original string print("The original string is : " + str(test_str)) # conditional combination for getting result. res = bool(re.match("^(?=.*[a-zA-Z])(?=.*[\d])[a-zA-Z\d]+$", "A530")) # printing result print("Does string contain both numbers and alphabets only? : " + str(res))
Producción
The original string is : Geeks4Geeks Does string contain both numbers and alphabets only? : True
Método #3: Usando el operador in
Python3
# Python3 code to demonstrate working of # Test if string contains both Numbers and Alphabets only # initializing string test_str = 'Geeks4Geeks' lowercasealphabets="abcdefghijklmnopqrstuvwxyz" uppercasealphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZ" digits="0123456789" # printing original string print("The original string is : " + str(test_str)) res=False al=0 dig=0 for i in test_str: if (i in lowercasealphabets) or (i in uppercasealphabets): al+=1 elif (i in digits) : dig+=1 if(al+dig==len(test_str)): res=True # printing result print("Does string contain both numbers and alphabets only? : " + str(res)) #contributed by Bhavya Koganti
Producción
The original string is : Geeks4Geeks Does string contain both numbers and alphabets only? : True
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