In this tutorial, we will learn how to delete text or characters from a given string in Python. Python’s string-handling capabilities make this task extremely easy. We will explore a few different methods to achieve this goal, including slicing, regular expressions, and string methods.
Step 1: Slicing the string
One way to delete characters from a string is to use slicing. Slicing takes two indices and creates a new substring with the characters between those indices.
Here’s the basic syntax for slicing a string:
1 |
new_string = original_string[start:stop] |
Suppose we want to delete the first three characters of a string:
1 2 3 |
original_string = "Hello, World!" new_string = original_string[3:] print(new_string) |
lo, World!
Here, we have sliced the string starting at index 3 and continuing until the end of the string, effectively removing the first three characters.
Step 2: Using regular expressions
Another method to delete text in Python is by using the re module, Python’s regular expressions library.
In this example, we will remove all non-digits characters from a string:
1 2 3 4 5 |
import re original_string = "Phone: 123-456-7890" new_string = re.sub(r'\D', '', original_string) print(new_string) |
1234567890
Here, we used the re.sub
function with the pattern \D
to match any non-digit character and replace them with an empty string.
Step 3: Using string methods
Python has a lot of built-in string methods that are useful for manipulating text. We can use these methods to delete certain characters or patterns from a string. In the following example, we will remove all whitespace characters from a string:
1 2 3 |
original_string = "Hello, World! How are you?" new_string = original_string.replace(' ', '') print(new_string) |
Hello,World!Howareyou?
In this example, we used the replace
method to replace all spaces with an empty string.
Full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Slicing original_string = "Hello, World!" new_string = original_string[3:] print(new_string) # Using regular expressions import re original_string = "Phone: 123-456-7890" new_string = re.sub(r'\D', '', original_string) print(new_string) # Using string methods original_string = "Hello, World! How are you?" new_string = original_string.replace(' ', '') print(new_string) |
Conclusion:
In this tutorial, we have seen different methods to delete text from a string in Python, such as slicing, using regular expressions, and using built-in string methods. Depending on the specific problem, you might want to use one of these methods or even combine them for more advanced text manipulation.