Test if String Contains Alphabets and Spaces - Python
Last Updated :
17 Jan, 2025
We are given a string and the task is to determine whether it contains only alphabets and spaces, this is often required when working with datasets where the string must not include any digits, punctuation or special characters.
Using all() isspace() and isalpha()
This method iterates through each character in the string, checking whether all characters are either alphabets (isalpha()
) or spaces (isspace()
) and the all()
function ensures the condition holds true for the entire string.
Python
s = "geeksforgeeks is best for geeks"
# Check if all characters are alphabets or spaces
res = s != '' and all(c.isalpha() or c.isspace() for c in s)
print("Does the string contain only alphabets and spaces:", res)
OutputDoes the string contain only alphabets and spaces: True
Explanation:
all()
function ensures that every character in the string is either an alphabet or a spacechr.isalpha() or chr.isspace()
checks whether each character is alphabetic or a space
Using Regular Expressions
In this method we are using re.match()
to match the string against a regular expression that allows only alphabets and spaces. ( regex pattern [a-zA-Z\s]+$
ensures that only alphabetic characters and spaces are allowed in the string.)
Python
import re
s = 'geeksforgeeks is best for geeks'
# Test if String contains Alphabets and Spaces
res = bool(re.match('[a-zA-Z\s]+$', s))
print("Does String contain only space and alphabets : " + str(res))
OutputDoes String contain only space and alphabets : True
Explanation: re.match()
function attempts to match the pattern at the start of the string and returns a boolean indicating whether the entire string contains the pattern or not.
Using operator.countOf()
Method
This method uses the operator.countOf()
function to check whether each character in the string is either an alphabet or a space.
Python
import operator as op
s = "geeksforgeeks is 3best for geeks" # String to check
a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" # All alphabets
sp = " " # Space character
# Check if all characters are alphabets or spaces
res = s != ' ' and all(op.countOf(a, c) > 0 or op.countOf(sp, c) > 0 for c in s)
print("Does the string contain only alphabets and spaces:", res)
OutputDoes the string contain only alphabets and spaces: False
Explanation:
all(...)
ensures every character is either in the allowed alphabets (a
) or is a space (sp
).s != ' '
is used to make sure that the string is not empty before the check
Using filter()
and a Lambda Function
In this method we use the filter()
function combined with a lambda function to check if all characters in the string belong to the set of allowed characters (alphabets and spaces).
Python
s = "geeksforgeeks is best for geeks"
chars = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ") # Allowed characters
# Filter out characters not in the allowed set
res = ''.join(filter(lambda c: c in chars, s)) == s
print("Does the string contain only alphabets and spaces:", res)
OutputDoes the string contain only alphabets and spaces: True
Explanation:
filter(lambda c: c in allowed_chars, s)
filters only allowed characters from the string.- The result is compared with the original string to ensure no invalid characters are present.
Using reduce()
Method and Lambda Function
In this method we utilize the reduce()
function from the functools
module to iteratively check whether all characters in the string are either alphabets or spaces.
Python
from functools import reduce
s = "geeksfo1rgeeks is best for geeks"
# Use reduce to verify all characters are alphabets or spaces
res = reduce(lambda x, y: x and (y.isalpha() or y.isspace()), s, True)
print("Does the string contain only alphabets and spaces:", res)
OutputDoes the string contain only alphabets and spaces: False
Similar Reads
Separate Alphabets and Numbers in a String - Python The task is to separate alphabets and numbers from a string. For example, given "a1b2c3", the output should be alphabets "abc" and numbers "123".Using List ComprehensionList comprehension offers a concise and efficient way to separate alphabets and numbers from a string. It iterates through each cha
2 min read
Python - Add space between Numbers and Alphabets in String In this article, we delve into a practical Python solution to improve text readability by adding spaces between numbers and alphabets in strings by utilizing Python's powerful string manipulation capabilities. Input: test_str = 'ge3eks4geeks is1for10geeks' Output: ge 3 eks 4 geeks is 1 for 10 geeks
9 min read
Python | Alternate vowels and consonants in String Sometimes, while working with Strings in Python, we can have a problem in which we may need restructure a string, adding alternate vowels and consonants in it. This is a popular school-level problem and having solution to this can be useful. Let's discuss certain ways in which this problem can be so
7 min read
Python | Ways to check string contain all same characters Given a list of strings, write a Python program to check whether each string has all the characters same or not. Given below are a few methods to check the same. Method #1: Using Naive Method [Inefficient] Python3 # Python code to demonstrate # to check whether string contains # all characters same
5 min read
Python - Test if String contains any Uppercase character The goal is to check if a given string contains at least one uppercase letter (A-Z). Using any() and isupper()any() function, combined with isdigit(), checks if any character in a string is a digit. It efficiently scans the string and returns True if at least one digit is found.Python# Define the in
3 min read
Python - All possible space joins in String Sometimes, while working with Python Strings, we can have a problem in which we need to construct strings with a single space at every possible word ending. This kind of application can occur in domains in which we need to perform testing. Let us discuss certain ways in which this task can be perfor
8 min read