Check if string contains only Letters and Spaces in Python

avatar

Borislav Hadzhiev

Last updated: Sep 18, 2022

banner

Photo from Unsplash

Check if string contains only Letters and Spaces in Python #

To check if a string contains only letters and spaces:

  1. Use a generator expression to iterate over the string.
  2. Check if each character is a letter or a space.
  3. If the condition is met for all characters, the string contains only letters and spaces.
main.py
def only_letters_and_spaces(string): return all(char.isalpha() or char.isspace() for char in string) if only_letters_and_spaces('a b c'): # 👇️ this runs print('The string contains only letters and spaces') else: print('The string does NOT contain only letters and spaces') print(only_letters_and_spaces('bobby hadz')) # 👉️ True print(only_letters_and_spaces('')) # 👉️ True print(only_letters_and_spaces(' ')) # 👉️ True print(only_letters_and_spaces('bobby_hadz')) # 👉️ False print(only_letters_and_spaces('bobby123')) # 👉️ False

We used a generator expression to iterate over the string.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we use the str.isalpha() and str.isspace() methods to check if the current character is a letter or a space.

The str.isalpha() method returns True if all characters in the string are alphabetic and there is at least one character, otherwise False is returned.

main.py
print('BOBBY'.isalpha()) # 👉️ True # 👇️ contains space print('BOBBY HADZ'.isalpha()) # 👉️ False

The str.isalpha method considers alphabetic characters the ones that are defined in the Unicode character database as "Letter".

The str.isspace method returns True if there are only whitespace characters in the string and there is at least one character, otherwise False is returned.

main.py
print(' '.isspace()) # 👉️ True print(''.isspace()) # 👉️ False print('b'.isspace()) # 👉️ False

The all() built-in function takes an iterable as an argument and returns True if all elements in the iterable are truthy (or the iterable is empty).

main.py
def only_letters_and_spaces(string): return all(char.isalpha() or char.isspace() for char in string) print(only_letters_and_spaces('bobby hadz')) # 👉️ True print(only_letters_and_spaces('')) # 👉️ True print(only_letters_and_spaces(' ')) # 👉️ True print(only_letters_and_spaces('bobby_hadz')) # 👉️ False print(only_letters_and_spaces('bobby123')) # 👉️ False

Notice that the all() function returns True if the string is empty.

If you need to handle this scenario, check for the string's length.

main.py
def only_letters_and_spaces(string): return ( len(string) > 0 and all(char.isalpha() or char.isspace() for char in string) ) print(only_letters_and_spaces('bobby hadz')) # 👉️ True print(only_letters_and_spaces('')) # 👉️ False

The updated function returns True only if the string is not empty and contains only letters and spaces.

Alternatively, you can use a regular expression.

Check if string contains only Letters and Spaces using re.match() #

Use the re.match() method to check if a string contains only letters and spaces, e.g. re.match(r'^[a-zA-Z ]+$', string). The re.match method will return a match object if the string contains only letters and spaces, otherwise None is returned.

main.py
import re def only_letters_and_spaces(string): return bool(re.match(r'^[a-zA-Z ]+$', string)) if only_letters_and_spaces('a b c'): # 👇️ this runs print('The string contains only letters and spaces') else: print('The string does NOT contain only letters and spaces') print(only_letters_and_spaces('bobby hadz')) # 👉️ True print(only_letters_and_spaces(' ')) # 👉️ True print(only_letters_and_spaces('')) # 👉️ False print(only_letters_and_spaces('bobby_hadz')) # 👉️ False print(only_letters_and_spaces('bobby123')) # 👉️ False

The re.match method returns a match object if the provided regular expression is matched in the string.

The match() method returns None if the string does not match the regex pattern.

The first argument we passed to the re.match method is a regular expression.

main.py
import re def only_letters_and_spaces(string): return bool(re.match(r'^[a-zA-Z ]+$', string))

The square brackets [] are used to indicate a set of characters.

The a-z and A-Z characters represent lowercase and uppercase ranges of letters.

Notice that we included a space after the letter ranges.

The caret ^ matches the start of the string and the dollar sign $ matches the end of the string.

The plus + causes the regular expression to match 1 or more repetitions of the preceding character (the letter ranges and the space).

You can also tweak the regular expression if you have to. Here is an example that checks if the string contains only letters, spaces, underscores and hyphens.

main.py
import re def only_letters_and_spaces(string): return bool(re.match(r'^[a-zA-Z _-]+$', string)) print(only_letters_and_spaces('_bobby hadz-')) # 👉️ True

If you need to tweak the regular expression, add the characters you want to match between the square brackets.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.