To keep only alphabets in a string in Python, you can use regular expressions from the 're' module to remove non-alphabetic characters.
In this example,
str1
with a value of "Hello123 World"
.[^a-zA-Z]
to match non-alphabetic characters.sub()
method from the 're' module to replace all non-alphabetic characters with an empty string.str1
.import re
str1 = "Hello123 World"
str1 = re.sub('[^a-zA-Z]', '', str1)
print('Modified string:', str1)
Modified string: HelloWorld
In this example,
str2
with a value of "apple@banana"
.[^a-zA-Z]
to match non-alphabetic characters.sub()
method from the 're' module to replace all non-alphabetic characters with an empty string.str2
.import re
str2 = "apple@banana"
str2 = re.sub('[^a-zA-Z]', '', str2)
print('Modified string:', str2)
Modified string: applebanana
In this tutorial, we learned How to keep only Alphabets in a String in Python language with well detailed examples.