When writing Python code, developers often need to modify string data. Common string modifications include:
In this guide, we will focus on the first transformation—deleting characters from a string in Python.
It’s important to note that strings in Python are immutable, meaning that any method or function that modifies a string will return a new string object with the changes applied.
This section covers the main methods in Python used for deleting characters from a string. We will explore the following methods:
replace()
translate()
re.sub()
For each method, we will explain the syntax and provide practical examples.
The first Pyhton method we will discuss is replace()
. It is used to replace specific characters in a string with others. Since strings are immutable, replace()
returns a new string object with the modifications applied.
Syntax:
original_string.replace(old, new[, count])
Where:
original_string
– The string where modifications will take placeold
– The substring to be replacednew
– The substring that will replace oldcount
(optional) – The number of occurrences to replace (if omitted, all occurrences will be replaced)First, let’s remove all spaces from the string "H o s t m a n":
example_str = "H o s t m a n"
result_str = example_str.replace(" ", "")
print(result_str)
Output:
Hostman
We can also use the replace()
method to remove newline characters (\n
).
example_str = "\nHostman\nVPS"
print(f'Original string: {example_str}')
result_str = example_str.replace("\n", " ")
print(f'String after adjustments: {result_str}')
Output:
Original string:
Hostman
VPS
String after adjustments: Hostman VPS
The replace()
method has an optional third argument, which specifies the number of replacements to perform.
example_str = "Hostman VPS Hostman VPS Hostman VPS"
print(f'Original string: {example_str}')
result_str = example_str.replace("Hostman VPS", "", 2)
print(f'String after adjustments: {result_str}')
Output:
Original string: Hostman VPS Hostman VPS Hostman VPS
String after adjustments: Hostman VPS
Here, only two occurrences of "Hostman VPS" were removed, while the third occurrence remained unchanged.
We have now explored the replace()
method and demonstrated its usage in different situations. Next, let’s see how we can delete and modify characters in a string using translate()
.
The Python translate()
method functions similarly to replace()
but with additional flexibility. Instead of replacing characters one at a time, it allows mapping multiple characters using a dictionary or translation table. The method returns a new string object with the modifications applied.
Syntax:
original_string.translate(mapping_table)
In the first example, let’s remove all occurrences of the $
symbol in a string and replace them with spaces:
example_str = "Hostman$Cloud$—$Cloud$Service$Provider."
print(f'Original string: {example_str}')
result_str = example_str.translate({ord('$'): ' '})
print(f'String after adjustments: {result_str}')
Output:
Original string: Hostman$Cloud$—$Cloud$Service$Provider.
String after adjustments: Hostman Cloud — Cloud Service Provider.
To improve code readability, we can define the mapping table before calling translate()
. This is useful when dealing with multiple replacements:
example_str = "\nHostman%Cloud$—$Cloud$Service$Provider.\n"
print(f'Original string: {example_str}')
# Define translation table
example_table = {ord('\n'): None, ord('$'): ' ', ord('%'): ' '}
result_str = example_str.translate(example_table)
print(f'String after adjustments: {result_str}')
Output:
Original string:
Hostman%Cloud$—$Cloud$Service$Provider.
String after adjustments: Hostman Cloud — Cloud Service Provider.
In addition to replace()
and translate()
, we can use regular expressions for more advanced character removal and replacement. Python's built-in re module provides the sub()
method, which searches for a pattern in a string and replaces it.
Syntax:
re.sub(pattern, replacement, original_string [, count=0, flags=0])
pattern
– The regular expression pattern to matchreplacement
– The string or character that will replace the matched patternoriginal_string
– The string where modifications will take placecount
(optional) – Limits the number of replacements (default is 0, meaning replace all occurrences)flags
(optional) – Used to modify the behavior of the regex searchLet's remove all whitespace characters (\s
) using the sub()
method from the re module:
import re
example_str = "H o s t m a n"
print(f'Original string: {example_str}')
result_str = re.sub('\s', '', example_str)
print(f'String after adjustments: {result_str}')
Output:
Original string: H o s t m a n
String after adjustments: Hostman
In addition to using various methods to delete characters, Python also allows the use of slices. As we know, slices extract a sequence of characters from a string.
To delete characters from a string by index in Python, we can use the following slice:
example_str = "\nHostman \nVPS"
print(f'Original string: {example_str}')
result_str = example_str[1:9] + example_str[10:]
print(f'String after adjustments: {result_str}')
In this example, we used slices to remove newline characters. The output of the code:
Original string:
Hostman
VPS
String after adjustments: Hostman VPS
Apart from using two slice parameters, you can also use a third one, which specifies the step size for index increments. For example, if we set the step to 2, it will remove every odd-indexed character in the string. Keep in mind that indexing starts at 0.
Example:
example_str = "Hostman Cloud"
print(f'Original string: {example_str}')
result_str = example_str[::2]
print(f'String after adjustments: {result_str}')
Output:
Original string: Hostman Cloud
String after adjustments: HsmnCod
In this guide, we learned how to delete characters from a string in Python using different methods, including regular expressions and slices. The choice of method depends on the specific task. For example, the replace()
method is suitable for simpler cases, while re.sub()
is better for more complex situations.