Python | Ways to check if given string contains only letter

Python | Ways to check if given string contains only letter

There are several ways to check if a given string contains only letters in Python. Here are some methods:

1. Using str.isalpha():

The str.isalpha() method returns True if all the characters in the string are letters and the string is not empty, otherwise, it returns False.

s = "Hello" print(s.isalpha()) # True s = "Hello123" print(s.isalpha()) # False 

2. Using Regular Expressions:

You can employ the re module to use regular expressions for checking if a string contains only letters.

import re def is_only_letters(s): return bool(re.match('^[a-zA-Z]+$', s)) s = "Hello" print(is_only_letters(s)) # True s = "Hello123" print(is_only_letters(s)) # False 

3. Using a for loop:

You can iterate over each character of the string and check if it's a letter.

def is_only_letters(s): for char in s: if not char.isalpha(): return False return True if s else False s = "Hello" print(is_only_letters(s)) # True s = "Hello123" print(is_only_letters(s)) # False 

4. Using all() with List Comprehension:

You can use list comprehension combined with the all() function to check if all characters in the string are letters.

def is_only_letters(s): return all([char.isalpha() for char in s]) and bool(s) s = "Hello" print(is_only_letters(s)) # True s = "Hello123" print(is_only_letters(s)) # False 

The str.isalpha() method is the most direct and efficient way to check if a string contains only letters. However, depending on the specific needs and constraints of a task, one might opt for other methods.


More Tags

samsung-galaxy regularized soapui razor-components snakecasing android-audiorecord deep-linking async-await pseudo-element field

More Programming Guides

Other Guides

More Programming Examples