Check if String contains only Alphabets in Python


Python - Check if String contains only Alphabets

To check if a string contains only alphabets, use the string isalpha() method. isalpha() returns boolean value of True if the string contains only alphabets, or False otherwise.

In this tutorial, we will write Python programs to check if the given string contains only alphabets (upper or lower).

Python - Check if String contains only alphabets

Syntax of isalpha()

The syntax of String.isalpha() function is given below.

bool = str1.isalpha()

Examples

1. Check if string contains only alphabets using string isalpha() method in Python

In this example, we are given a string in x, and we have to check if this string contains only alphabets using string isalpha() method.

Steps

  1. We are given a string value in variable x.
  2. Call isalpha() method on string x, and use the returned value as a condition in if else statement.
  3. In the if-block, write required code that needs to be run when the string contains only alphabets. We shall just write a print statement for this example.
  4. In the else-block, write required code that needs to be run when the string does not contain only alphabets. We shall just write a print statement.

Program

The complete program to check if given string contains only alphabets using string isalpha() method.

Python Program

# Given string
x = "HelloWorld"

# Check if string contains only alphabets
if x.isalpha():
    print('Given string contains only alphabets.')
else:
    print('Given string does not contain only alphabets.')

Output

Given string contains only alphabets.

Since the given string value in x has only alphabetic characters, x.isalpha() returned True, and the if-block is run.

2. Check if string contains only alphabets [Negative Scenario]

In this example, we have taken a string value in x, such that it contains some non-alphabetic characters as well. The program is same as that of in the previous example, just the string value is changed.

Python Program

# Given string
x = "Hello World! Good morning."

# Check if string contains only alphabets
if x.isalpha():
    print('Given string contains only alphabets.')
else:
    print('Given string does not contain only alphabets.')

Output

Given string does not contain only alphabets.

The string in x has some non-alphabetic characters like period character, white spaces, etc. Therefore x.isalpha() returned False, and the else-block is run.

Summary

In this tutorial of Python Examples, we learned how to check if a string contains only alphabets or not, using string isalpha() method, with the help of well detailed Python example programs.