How do I remove letters from a string in Python?
we can remove letters by using two methods-
- Using string replace () function
- Using string translate () function
We can use string replace() function to replace a character with a new character. If we provide an empty string as the second argument, then the character will get removed from the string.
Note- If need any programming assignment help
Note- If need any programming assignment help
Note that the string is immutable in Python, so this function will return a new string and the original string will remain unchanged.
- s = 'abc12321cba'
- print(s.replace('a', ''))
Output:
bc12321cb
Python Remove Character from String using translate()
Python string translate() function replace each character in the string using the given translation table. We have to specify the Unicode code point for the character and ‘None’ as a replacement to remove it from the result string. We can use ord() function to get the Unicode code point of a character.
- s = 'abc12321cba'
- print(s.translate({ord('a'): None}))
Output:
bc12321cb
If you want to replace multiple characters, that can be done easily using an iterator. Let’s see how to remove characters ‘a’, ‘b’ and ‘c’ from a string.
- s = 'abc12321cba'
- print(s.translate({ord(i): None for i in 'abc'}))
Comments
Post a Comment