How to Remove Letters From a String in Python
Given a string, the task is to remove one or more specific letters from it. Since Python strings are immutable, a new string must be created after removing characters.
For example:
Input: "hello world"
Remove: "l"
Output: "heo word"
Let’s explore different methods to remove letters from a string in Python.
Using replace()
The replace() method replaces all occurrences of a character with another replacing it with an empty string effectively removes it.
s = "hello world"
s = s.replace("l", "")
print(s)
Output
heo word
Explanation:
- s.replace("l", "") replaces every "l" with an empty string "".
- Since replacement creates a new string, the original remains unchanged.
Using filter() function
filter() function provides an efficient way to filter out characters based on a condition. It returns an iterator, which can be converted back to a string.
s = "hello world"
s = "".join(filter(lambda c: c != "o", s))
print(s)
Output
hell wrld
Explanation:
- filter(lambda c: c != "o", s) checks every character in s and removes 'o'.
- join() merges the remaining characters back into a single string.
- Works well for both letters and conditions (like removing vowels, digits, etc.).
Using Regular Expressions
For more advanced removal, such as removing multiple letters or patterns, the re.sub() method can be used. It is used for pattern-based deletions.
import re
s = "hello world"
s = re.sub("[aeiou]", "", s)
print(s)
Output
hll wrld
Explanation:
- re.sub("[aeiou]", "", s) removes all vowels.
- The pattern [aeiou] matches any vowel, and "" replaces them with nothing.
Using list comprehension
List comprehension provides a more concise way to remove specific characters from a string than the loop method.
s = "hello world"
s = "".join([c for c in s if c != "o"])
print(s)
Output
hell wrld
Explanation:
- [c for c in s if c != "o"] generates a list of characters in s but excludes "o".
- "".join(...) combines the list back into a string.
Related Articles: