Check if character is alphabet in Python
In this post, we have explained how to check if characters in a string are alphabetical or not and understand their uses with the help of examples.
While developing software, one might need to check whether the handling strings contain only alphabets, excluding some special characters or numbers. For example, name validation requires only alphabetic characters. Similarly, domain validation may require only alphabetic characters. Python is rich in built-in methods for string handling. The isalpha() method is one of them that returns true if all the characters in the string are alphabets. If not, it returns false.
Syntax of isalpha() in Python
val.isalpha()
Parameters: None
This function basically checks if the arguments include only alphabetic letters (both uppercase and lowercase).
The isalpha() method returns true, if all characters in the string are alphabets and false, if at least one character is not alphabet.
Python program to check if character is alphabet
The given Python program demonstrates the working of the isalpha() method.
name1 = "AvyanshKashyap"
print(name1.isalpha())
# contains whitespace
name2 = "Arden Smith 12333"
print(name2.isalpha())
Output of the above code:
True
False
Real life example to check if character is alphabet
Here, we have taken a real life example of validating first name and last name of the user.
# Python program to validate the first name and last name using isalpha() method
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
if first_name.isalpha() == True and last_name.isalpha() == True:
print('All characters are alphabets')
else:
print('Name should be in alphabet only.')
Output of the above code:
True
False
Python remove non-alphabetic characters
We can also remove non-alphabetic characters from string using Python isalpha() method. In the given program, we have taken a string that contains non-alphabetic characters. We looped over the string and filtered the string using the isalpha() method.
name='Kelvin Luise@ 1234'
count=0
validname=""
for s in name:
if (s.isalpha()) == True:
count+=1
validname+=s
print(validname)
Output of the above code:
KelvinLuise
Related Articles
Python program to find the median of three valuesMerge sort program in Python
Bubble sort program in Python
Python convert list to numpy array
Python Numpy Array Shape
Python NumPy: Overview and Examples
Convert Python list to numpy array
numpy dot product
Trigonometric functions Python Numpy
Python Pandas Dataframe to CSV
Python Pandas DataFrame
Convert list to dictionary Python
Python dict inside list
Convert dictionary to dataframe Python
Python Pandas CSV to Dataframe
Convert List to Dataframe Python
Python add list to list
Difference between tuple and list in Python
Convert Excel to CSV Python Pandas
Alphabetical order Python
Python | Generate QR Code using pyqrcode module