Although strings are immutable in Python, you can create new strings on the basis of existing ones. Using different methods, you can remove or replace char­ac­ters to create the string you want.

What does im­mut­ab­il­ity mean?

Im­mut­ab­il­ity means that once an object has been created, it can no longer be changed. In Python, strings are immutable. When you remove char­ac­ters from a string using methods in Python, you’re es­sen­tially creating a new string with specific elements of the original. The original string remains unchanged though. String im­mut­ab­il­ity aids efficient memory man­age­ment and prevents un­ex­pec­ted outcomes when handling strings.

How to remove and replace in­di­vidu­al char­ac­ters or a set of char­ac­ters

To remove certain char­ac­ters from a string, you can use str.replace() or re.sub() with a regular ex­pres­sion that rep­res­ents the char­ac­ters or patterns that you want to remove.

str.replace()

The str.replace() function is used to remove parts of a text and replace it with a substring.

original_string = "Hello, Python#"
 
modified_string = original_string.replace('#', '!')
print(original_string)  # Output: Hello, Python#
print(modified_string)  # Output: Hello, Python!
Python

In the example above, the replace() method swaps out the character ‘#’ in original_string with an ex­clam­a­tion mark ‘!’.

re.sub()

The re.sub() function belongs to the re module in Python. With this function, you can search for regular ex­pres­sions in strings and replace them with other char­ac­ters.

import re
original_string = "Hello, World! @#$%^&*"
modified_string = re.sub(r'[@#$%^&*]', '', original_string)
print(original_string)  # Output: Hello, World! @#$%^&*
print(modified_string)  # Output: Hello, World!
Python

The pattern [@#$%^&*] is a regular ex­pres­sion that matches the special char­ac­ters @, #, $, %, ^, &,*. The re.sub() function searches for all matches of the pattern in the original string original_string and replaces them with an empty string ''. In the example above, we saved the result in the variable modified_string and output it.

How to remove all char­ac­ters except letters

You can use different methods to remove all the letters from a string. Below we’ll take a look at how to do this with the following methods: isalpha(), filter() and re.sub().

re.sub()

import re
original_string = "Hello, 123 World! @#$%^&*"
modified_string = re.sub(r'[^a-zA-Z]', '', original_string)
print(original_string) # Output: Hello, 123 World! @#$%^&*
print(modified_string) # Output: HelloWorld
Python

The regular ex­pres­sion [^a-zA-Z] matches any character that is not a lowercase or uppercase letter. As a result, modified_string is only made up of the letters from the original string. Keep in mind that this removes the spaces between the letters as well.

isalpha()

original_string = "Hello, 123 World! @#$%^&*"
modified_string = ''.join(char for char in original_string if char.isalpha())
print(original_string) # Output: Hello, 123 World! @#$%^&*
print(modified_string) # Output: HelloWorld
Python

In this example, we used a list com­pre­hen­sion to iterate through each letter in original_string. The isalpha() method checks whether a character is a letter. The letters are then inserted into a new modified_string, while all other char­ac­ters are ignored.

filter()

original_string = "Hello, 123 World! @#$%^&*"
filtered_chars = filter(str.isalpha, original_string)
modified_string = ''.join(filtered_chars)
print(original_string) # Output: Hello, 123 World! @#$%^&*
print(modified_string) # Output: HelloWorld
Python

The str.isalpha() method returns True if the character is a letter, otherwise it returns False. The filter() function creates a filter object con­tain­ing only the char­ac­ters that satisfy the str.isalpha() condition. This allows us to remove all the char­ac­ters in original_string that aren’t letters.

How to remove all char­ac­ters except numbers

As in the previous examples, you can separate numbers using re.sub(), filter() and the numerical equi­val­ent to isalpha(), isdigit().

re.sub()

import re
original_string = "Hello, 123 World! @#$%^&*"
modified_string = re.sub('[^0-9]', '', original_string)
print(original_string) # Output: Hello, 123 World! @#$%^&*
print(modified_string) # Output: 123
Python

With 0-9, we can define a range that en­com­passes all digits from 0 to 9. The hyphen - between 0 and 9 acts as a range operator. The preceding ^ means all char­ac­ters not within the specified range from 0 to 9. These char­ac­ters are replaced by empty char­ac­ters using re.sub.

filter()

original_string = "Hello, 123 World! @#$%^&*"
filtered_chars = filter(str.isdigit, original_string)
modified_string = ''.join(filtered_chars)
print(original_string) # Output: Hello, 123 World! @#$%^&*
print(modified_string) # Output: 123
Python

The filter() function in com­bin­a­tion with isdigit() can filter numbers from a string and remove the remaining char­ac­ters. Using these together, the new string shows us the digits 123.

isdigit()

original_string = "Hello, 123 World"
modified_string = ''.join('*' if not char.isdigit() else char for char in original_string)
print(original_string) # Output: Hello, 123 World
print(modified_string) # Output: *******123******
Python

We can also use the isdigit() method in a list com­pre­hen­sion to iterate through each char in original_string. Char­ac­ters that are not decimal digits (not char.isdigit() is true) will be replaced with an asterisk *, otherwise they stay the same.

How to remove char­ac­ters using translate()

The translate() method is a built-in function in Python used for advanced character re­place­ment and trans­la­tion in strings. It provides an efficient way to replace char­ac­ters using a table of trans­la­tions.

original_string = "Hello, World! Remove vowels."
translation_table = str.maketrans(dict.fromkeys('aeiouAEIOU', '*'))
modified_string = original_string.translate(translation_table)
print(original_string) # Output: Hello, World! Remove vowels.
print(modified_string) # Output: H*ll*, W*rld! R*m*v* v*w*ls.
Python

In the example above, we used the str.maketrans() con­struct­or and dict.fromkeys() to create the trans­la­tion table. This specifies that all vowels are to be replaced by *. The table is then applied to the original string to get modified_string.

Tip

When filtering strings, you can use the Python string index to filter char­ac­ters in certain places. To format strings in a specific manner, take a look at our article on Python string formats.

Web hosting
The hosting your website deserves at an un­beat­able price
  • Loading 3x faster for happier customers
  • Rock-solid 99.99% uptime and advanced pro­tec­tion
  • Only at IONOS: up to 500 GB included
Go to Main Menu