To check if a string contains only alphabets in Python, you can use regular expressions or iterate through each character and check if it is an alphabet using functions like re.match
and str.isalpha
.
In this example,
re.match
function to check if the string matches the pattern.containsOnlyAlphabets
to True
, otherwise False
.import re
str1 = 'HelloWorld'
pattern = '^[A-Za-z]+$'
containsOnlyAlphabets = bool(re.match(pattern, str1))
print('String contains only alphabets:', containsOnlyAlphabets)
String contains only alphabets: True
In this example,
str2
with a value of 'Hello123'
.str.isalpha()
method.containsOnlyAlphabets
to True
, otherwise False
.str2 = 'Hello123'
containsOnlyAlphabets = all(char.isalpha() for char in str2)
print('String contains only alphabets:', containsOnlyAlphabets)
String contains only alphabets: False
In this tutorial, we learned How to Check if String contains only Alphabets in Python language with well detailed examples.