How to Remove Non-Alphabetic Characters from a String in Python?

Estimated read time 1 min read

You can remove non-alphabetic characters from a string in Python using regular expressions and the re module. Here’s an example:

import re

s = 'Hello, 123 World!'
new_s = re.sub(r'[^a-zA-Z]', '', s)
print(new_s) # Output: 'HelloWorld'

In this example, we have a string (s) that contains alphabetic and non-alphabetic characters, including spaces, digits, and punctuation. We want to remove all non-alphabetic characters from the string. We achieve this by using the sub() method from the re module, which replaces all occurrences of a regular expression pattern with a specified string. The regular expression pattern [^a-zA-Z] matches any character that is not an uppercase or lowercase letter. The replacement string is an empty string, which removes all non-alphabetic characters from the string. The resulting string contains only alphabetic characters.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply