DEV Community

ライフポータル
ライフポータル

Posted on • Originally published at code-izumi.com

Python String Manipulation: Every Way to Delete Specific Characters

When processing text data in Python, you frequently run into these scenarios:

  • "I want to remove extra whitespace."
  • "I need to bulk-delete specific symbols."
  • "I want to remove elements from a list that contain certain words."

While it all falls under "deletion," the method you should use depends on whether you are modifying a String or a List. Python has also introduced more intuitive methods in recent versions that make these tasks much simpler.

In this guide, we’ll dive into every major technique for deleting characters in Python, covering both string and list operations with practical code examples and modern best practices.


Basic Techniques for String Deletion

In Python, strings are immutable, meaning you cannot modify the original string directly. Instead, these methods return a new string with the characters removed.

1. replace(): Delete All Occurrences

To remove a specific character or substring everywhere it appears, use the replace() method by replacing it with an empty string "".

text = "Python-is-fun-and-powerful"

# Replace hyphen "-" with an empty string ""
cleaned_text = text.replace("-", "")

print(f"Original: {text}")
print(f"Cleaned : {cleaned_text}")
# Output: Pythonisfunandpowerful
Enter fullscreen mode Exit fullscreen mode

You can also limit the number of deletions by providing a third argument: text.replace("-", "", 2) will only remove the first two hyphens.

2. strip(): Remove Leading and Trailing Characters

To clean up unwanted characters (like spaces or newlines) only at the start or end of a string, use the strip family of methods:

  • strip(): Removes from both ends.
  • lstrip(): Removes from the left (start) only.
  • rstrip(): Removes from the right (end) only.
text = "   Hello Python!   "

print(f"strip : '{text.strip()}'")   # 'Hello Python!'
print(f"lstrip: '{text.lstrip()}'")  # 'Hello Python!   '
print(f"rstrip: '{text.rstrip()}'")  # '   Hello Python!'
Enter fullscreen mode Exit fullscreen mode

By default, these remove whitespace, but you can specify a set of characters like text.strip("*").

3. removeprefix() and removesuffix() (Python 3.9+)

Added in Python 3.9, these are the best practices for removing a specific word only if it appears at the very beginning or end of a string.

filename = "report_2026.txt"

# Remove prefix "report_"
name_only = filename.removeprefix("report_")

# Remove suffix ".txt"
base_name = filename.removesuffix(".txt")

print(f"Prefix removed: {name_only}") # 2026.txt
print(f"Suffix removed: {base_name}") # report_2026
Enter fullscreen mode Exit fullscreen mode

Unlike lstrip(), which treats the input as a set of individual characters to prune, removeprefix() treats it as a single exact string, making it much safer for filenames and IDs.


Advanced Pattern Deletion

1. translate(): Delete Multiple Different Characters at Once

If you need to delete a whole set of symbols (e.g., vowels or punctuation), chaining replace() multiple times is inefficient. Using translate() with str.maketrans() is much faster.

text = "p-y+t=h/o.n"

# Create a mapping table (the 3rd argument specifies characters to delete)
table = str.maketrans("", "", "-+=/.")

cleaned_text = text.translate(table)
print(cleaned_text) # python
Enter fullscreen mode Exit fullscreen mode

2. re.sub(): Regex-Based Deletion

For pattern-based deletion—like "remove all numbers" or "remove everything except letters"—the re (regular expression) module is your best friend.

import re

text = "Python 3.14 is released in 2025."

# Delete all digits (\d)
no_digits = re.sub(r"\d+", "", text)

# Delete everything except letters and spaces
only_alpha = re.sub(r"[^a-zA-Z\s]", "", text)

print(f"No digits: {no_digits}")
print(f"Letters only: {only_alpha}")
Enter fullscreen mode Exit fullscreen mode

Deleting Specific Elements from a List

When dealing with a list of strings, the logic changes from "modifying a string" to "filtering a collection."

1. remove() vs. pop()

  • remove(value): Deletes the first occurrence of a specific value.
  • pop(index): Deletes the element at a specific position and returns it.
fruits = ["apple", "banana", "orange", "banana"]

fruits.remove("banana") # Removes only the first banana
print(fruits) # ['apple', 'orange', 'banana']

removed_item = fruits.pop(1) # Removes 'orange'
print(fruits) # ['apple', 'banana']
Enter fullscreen mode Exit fullscreen mode

2. List Comprehension: Bulk Filtering

The most Pythonic way to remove all elements that meet a certain condition is to use a List Comprehension. Instead of "deleting," you "keep" the ones you want.

files = ["data.csv", "image.jpg", "backup.csv", "memo.txt"]

# Remove all files containing ".csv" (Keep files if ".csv" is NOT in f)
filtered_files = [f for f in files if ".csv" not in f]

print(filtered_files) # ['image.jpg', 'memo.txt']
Enter fullscreen mode Exit fullscreen mode

Conclusion

The right way to "delete" in Python depends on the scope. For exact matches in strings, replace() or removeprefix() are your best bets. For complex patterns, use re.sub(). When cleaning up lists, List Comprehension is almost always the most efficient and readable choice.


Originally published at: [https://code-izumi.com/python/delete-specific-character/]

Top comments (0)