learn python string isalpha() with example

The isalpha() method in Python is a built-in method used for string handling. The isalpha() method returns True if all the characters in the string are alphabets (either uppercase or lowercase), otherwise it returns False.

Syntax: 

string.isalpha()

How to use the isalpha() method:

string1 = "HelloWorld"
print(string1.isalpha()) # This will return True

string2 = "Hello World"
print(string2.isalpha()) # This will return False because of the space

string3 = "Hello123"
print(string3.isalpha()) # This will return False because of the number

Example 1

Using isalpha() to checking if the string is fully alphabetical.

str1 = "HelloWorld"
str2 = "Hello World"
str3 = "Hello123"

print(str1.isalpha()) # Output: True
print(str2.isalpha()) # Output: False
print(str3.isalpha()) # Output: False

Example 2

When you want to ensure user input is only alphabetic, such as for a name field.

# Let's assume you are getting a user input
user_input = input("Please enter a word: ")

# Check if the input is alphabetic
if user_input.isalpha():
  print("Your input is alphabetic.")
else:
  print("Your input contains non-alphabet characters.")

Example 3

isalpha() can be used in combination with a list comprehension to filter out non-alphabetic strings from a list.

strings = ["Hello", "World123", "Python", "123", "AI 2023"]

# And you want to filter out the strings that are fully alphabetic
alphabetic_strings = [s for s in strings if s.isalpha()]

print(alphabetic_strings) # Output: ['Hello', 'Python']