Last updated: Apr 9, 2024
Reading timeยท3 min
Use the re.sub()
method to remove the characters that match a regex from a
string.
The re.sub()
method will remove the matching characters by replacing them
with empty strings.
import re my_str = '!bobby @hadz #com $abc' result = re.sub(r'[!@#$]', '', my_str) print(result) # ๐๏ธ 'bobby hadz com abc' result = re.sub(r'[^!@#$]', '', my_str) print(result) # ๐๏ธ '!@#$'
The first example uses the re.sub()
method to remove the characters that match
a regular expression from a string.
The re.sub() method returns a new string that is obtained by replacing the occurrences of the pattern with the provided replacement.
import re my_str = '1bobby, 2hadz, 3com' result = re.sub(r'[0-9]', '', my_str) print(result) # ๐๏ธ 'bobby, hadz, com' result = re.sub(r'[a-zA-Z]', '', my_str) print(result) # ๐๏ธ '1, 2, 3'
If the pattern isn't found, the string is returned as is.
If you have specific characters you'd like to remove, add them between square brackets.
import re my_str = '!bobby @hadz #com $abc' result = re.sub(r'[!@#$]', '', my_str) print(result) # ๐๏ธ 'bobby hadz com abc' result = re.sub(r'[^!@#$]', '', my_str) print(result) # ๐๏ธ '!@#$'
The square brackets []
are used to indicate a set of characters.
The first example removes the specified characters by replacing them with empty strings.
The second example uses the caret ^
symbol.
^
at the beginning of the set means "NOT". In other words, match all characters that are NOT !
, @
, #
and $
.Alternatively, you can use a
generator expression
with the str.join()
method.
my_str = '!bobby @hadz #com $abc' characters_to_remove = '!@#$' result = ''.join( char for char in my_str if char not in characters_to_remove ) print(result) # ๐๏ธ 'bobby hadz com abc'
We used a generator expression to iterate over the string.
On each iteration, we check if the character is not one of the characters to be removed and return the result.
The in operator tests
for membership. For example, x in s
evaluates to True
if x
is a member of
s
, otherwise, it evaluates to False
.
x not in s
returns the negation of x in s
.print('abc' not in 'bobbyhadz.com') # ๐๏ธ True print('bob' not in 'bobbyhadz.com') # ๐๏ธ False
The last step is to use the str.join()
method to join the remaining strings.
my_str = '!bobby @hadz #com $abc' characters_to_remove = '!@#$' result = ''.join( char for char in my_str if char not in characters_to_remove ) print(result) # ๐๏ธ 'bobby hadz com abc'
The str.join() method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.
The string the method is called on is used as the separator between the elements.
We used an empty string as the separator between the elements because we want to join the remaining characters without a separator.
You can learn more about the related topics by checking out the following tutorials: