5 Different Ways to Remove Specific Characters From a String in Python

Using string methods, filter, and regexes

Indhumathy Chelliah
Oct 3, 2020 · 5 min read
Image for post
Image for post
Photo by Gary Chan on Unsplash

5 Different Ways to Remove Specific Characters From a String in Python

1. Remove specific characters from the string
2. Remove all characters except alphabets from a string
3. Remove all characters except the alphabets and the numbers from a string
4. Remove all numbers from a string useing a regular expression
5. Remove all characters from the string except numbers

1. Remove Specific Characters From the String

Using ‘str.replace’

Using str.replace(), we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str.replace() method will replace all occurrences of the specific character mentioned.

Image for post
Image for post
s="Hello$ Python3$"
s1=s.replace("$","")
print (s1)
#Output:Hello Python3

If we want to remove one occurrence of that character mentioned, mention the count:

str.replace(old,new,count)

s="Hello$ Python3$"
s1=s.replace("$","",1)
print (s1)
#Output:Hello Python3$

Using ‘re.sub()’

re.sub(pattern, repl, string, count=0, flags=0)

“Return the string obtained by replacing the leftmost nonoverlapping occurrences of pattern in the string by the replacement repl. If the pattern isn’t found, the string is returned unchanged.”

Python documentation

If we want to remove specific characters, the replacement string is mentioned as an empty string.

Image for post
Image for post
s="Hello$@& Python3$"
import
re
s1=re.sub("[$@&]","",s)
print (s1)
#Output:Hello Python3

s1=re.sub(“[$@&]”,””,s)

  • Pattern to be replaced → “[$@&]”
  • [] used to indicate a set of characters
  • [$@&] → will match either $ or @ or &
  • The replacement string is given as an empty string
  • If these characters are found in the string, they’ll be replaced with an empty string

2. Remove All Characters Except Alphabets From a String

Using ‘isalpha()’

Image for post
Image for post

isalpha() is used to check whether the string contains the alphabet or not. It returns True if it contains only the alphabet.

It’ll iterate through the string and check whether each character in the string is an alphabet or not and return it if it’s an alphabet.

Example

s="Hello$@ Python3&"
s1="".join(c for c in s if c.isalpha())
print (s1)
#Output:HelloPython

s=”Hello$@ Python3&”

(c for c in s if c.isalpha())

Result → [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]

It’s a generator expression. It returns a generator object containing all alphabets from the string.

s1=””.join(c for c in s if c.isalpha())

””.join will join all of the elements in the iterable using an empty string.

Using ‘filter()’

s="Hello$@ Python3&"
f=filter(str.isalpha,s)
s1="".join(f)
print (s1)

f=filter(str.isalpha,s)

The filter() function will apply the str.isalpha method to each element in the string, and if it’s True, it’ll return the item. Otherwise, it’ll skip the item.

s1=””.join(f)

filter() will return an iterator containing all of the alphabets in the string, and join() will join all of the elements in the iterator with an empty string.

Using ‘re.sub()’

Image for post
Image for post
s="Hello$@ Python3$"
import
re
s1=re.sub("[^A-Za-z]","",s)
print (s1)
#Output:HelloPython

s1=re.sub(“[^A-Za-z]”,””,s)

  • “[^A-Za-z]” → It’ll match all of the characters except the alphabets. If the first character of the set is '^', then all of the characters not in the set will be matched.
  • All of the characters matched will be replaced with an empty string
  • All of the characters except the alphabets are removed

3. Remove All Characters Except the Alphabets and the Numbers From a String

Using ‘isalnum()’

Image for post
Image for post

isalnum() is used to check whether characters in the string are alphanumeric (alphabets [A-Z, a-z] and numbers [0-9] are alphanumeric).

It’ll iterate through the string and check whether each character in the string is alphanumeric or not and return it if it’s an alphabet/number.

s="Hello$@ Python3&"
s1="".join(c for c in s if c.isalnum())
print (s1)
#Output:HelloPython3

Using ‘re.sub()’

s="Hello$@ Python3&_"
import
re
s1=re.sub("[^A-Za-z0-9]","",s)
print (s1)#Output:HelloPython3

s1=re.sub(“[^A-Za-z0–9]”,””,s)

  • “[^A-Za-z0–9]” → It’ll match all of the characters except the alphabets and the numbers. If the first character of the set is '^', then all of the characters not in the set will be matched.
  • All of the characters matched will be replaced with an empty string
  • All of the characters except the alphabets and numbers are removed

4. Remove All Numbers From a String Using a Regular Expression

Using ‘re.sub()’

Image for post
Image for post
s="Hello347 Python3$"
import
re
s1=re.sub("[0-9]","",s)
print (s1)
#Output:Hello Python$

s1=re.sub(“[0–9]”,””,s)

  • [0–9] will match the numbers from 0-9
  • re.sub(“[0–9]”,””,s, if found, will be replaced with an empty string

5. Remove All Characters From the String Except Numbers

Using ‘isdecimal()’

isdecimal() returns True if all characters in the string are decimals and there’s at least one character. Otherwise, it returns False. The decimal numbers are numbers that can be used to form numbers in base-10.

Image for post
Image for post

Example

s="1-2$3%4 5a"
s1="".join(c for c in s if c.isdecimal())
print (s1)
#Output:12345

s1=””.join(c for c in s if c.isdecimal())

It iterates through the string and checks whether each character in the string is a number or not and returns it if it’s a number.

””.join() will join all of the elements returned with an empty string

Using ‘re.sub()’

s="1-2$3%4 5a"
import
re
s1=re.sub("[^0-9]","",s)
print (s1)
#Output:12345

s1=re.sub(“[^0–9]”,””,s)

  • [^0–9] will match all characters except numbers 0-9
  • re.sub(“[^0–9]”,””,s: If any character that’s not a number is found, it’ll be replaced with an empty string

Using ‘filter()’

s="1-2$3%4 5a"
f=filter(str.isdecimal,s)
s1="".join(f)
print (s1)
#Output:12345

f=filter(str.isdecimal,s)

The filter() function will apply the str.isdecimal method to each element in the string, and if it’s True, it’ll return the item. Otherwise, it’ll skip the item.

s1=””.join(f)

filter() will return an iterator containing all of the numbers in the string, and join() will join all of the elements in the iterator with an empty string.

Refer to my story for filter() versus filterfalse().

Note: Python strings are immutable, so all of the about mentioned methods will remove characters from the string and return a new string. It won’t modify the original string.

Resources (Python Documentation)

Better Programming

Advice for programmers.

Sign up for The Best of Better Programming

By Better Programming

A weekly newsletter sent every Friday with the best articles we published that week. Code tutorials, advice, career opportunities, and more! Take a look

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Thanks to Zack Shapiro

Indhumathy Chelliah

Written by

Machine Learning | Artificial Intelligence | Python https://indhumathychelliah.com/

Better Programming

Advice for programmers.

Indhumathy Chelliah

Written by

Machine Learning | Artificial Intelligence | Python https://indhumathychelliah.com/

Better Programming

Advice for programmers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store