October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Remove Characters from a String in Python

Use the right Python string method for the job: replace exact substrings, trim edge characters, remove an exact affix, or delete selected characters throughout.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use replace() to remove an exact substring throughout a string, a strip() method to trim characters from its edges, removeprefix() or removesuffix() to remove one exact prefix or suffix, and translate() to delete selected characters anywhere. Python strings are not changed in place, so assign the returned string if you need to keep the result.

Choose a method by where and what you want to remove

Goal Method What the argument means
Remove an exact substring wherever it appears replace(old, '') An exact substring; all matches by default
Remove selected characters at either edge strip(chars) A set of individual characters allowed to be trimmed
Remove selected characters at the left or right edge lstrip(chars) or rstrip(chars) A set of individual characters allowed to be trimmed from that edge
Remove one exact prefix or suffix removeprefix(prefix) or removesuffix(suffix) One exact affix; requires Python 3.9 or later
Delete selected characters anywhere translate(str.maketrans('', '', chars)) A set of individual characters to delete throughout the string

Remove an exact substring with replace()

replace(old, new) returns a string with occurrences of old replaced by new. Pass an empty string as new to delete the match. By default, every occurrence is replaced; the optional third argument limits how many replacements are made.

text = "one-abc-two-abc"

cleaned = text.replace("abc", "")       # "one--two-"
first_only = text.replace("abc", "", 1)  # "one--two-abc"

This targets the exact sequence you pass, even when it occurs in the middle of the string. It is a different operation from trimming characters off an edge.

Trim characters from the ends with strip()

Use strip(chars) to trim characters from both ends, lstrip(chars) for the left edge, or rstrip(chars) for the right edge. The chars argument is treated as a set of individual characters, not as one literal prefix or suffix. Trimming continues at the selected edge while its next character belongs to that set.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
text = "...Hello, Python!!!"

both = text.strip(".! ")    # "Hello, Python"
left = text.lstrip(". ")    # "Hello, Python!!!"
right = text.rstrip("! ")  # "...Hello, Python"

With no argument, these methods trim whitespace at the relevant edge. Providing a character set changes what can be trimmed; for example, strip(" .,!? ") trims those punctuation and space characters from both ends, not from the middle.

Why rstrip(suffix) may remove too much

If you mean a literal suffix, do not use rstrip(suffix): its argument is a character set. The Python documentation illustrates the difference: 'Monty Python'.rstrip(' Python') produces 'M', because those characters are stripped repeatedly from the right. For one exact suffix, use removesuffix().

Remove one exact prefix or suffix

Use removeprefix(prefix) or removesuffix(suffix) when the target is one exact string at the beginning or end. Each removes a single matching affix and otherwise leaves the content unchanged. Both methods are available in Python 3.9 and later.

text = "prefix:report.txt"

without_prefix = text.removeprefix("prefix:")  # "report.txt"
without_suffix = text.removesuffix(".txt")      # "prefix:report"

For Python versions earlier than 3.9, check the beginning or end explicitly before slicing:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
prefix = "prefix:"
without_prefix = text[len(prefix):] if text.startswith(prefix) else text

suffix = ".txt"
without_suffix = text[:-len(suffix)] if text.endswith(suffix) else text

Delete selected characters throughout the string

To delete any occurrence of specific characters, wherever they appear, create a translation table that maps those characters to deletion and pass it to translate(). The third argument to str.maketrans() defines characters to map to None.

text = "beautiful day"
cleaned = text.translate(str.maketrans("", "", "aeiou"))
# "btfl dy"

This removes each listed character everywhere, unlike strip(), which works only at an edge. It also differs from replace(), which targets an exact substring.

Keep the result by assigning it

Python strings are immutable: these string methods return a new string rather than modifying the original. To retain the changed value, assign the result to a variable, as in text = text.replace("x", "") or cleaned = text.strip("."). If you do not assign or otherwise use the returned value, the original variable still refers to its original string.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Python reference

The official Python 3.14.8 built-in types documentation describes the behavior of these string methods and str.maketrans(). It identifies removeprefix() and removesuffix() as added in Python 3.9.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.