How to Remove Characters From a String in Python

Techwalla may earn compensation through affiliate links in this story.
Image Credit: skynesher/E+/GettyImages

In the Python programming language, there are several ways to remove characters from a string. If you want to remove specific characters from the beginning or end of a string, use the Python string strip family of functions. In general, you can use Python string manipulation tools to cut out particular characters anywhere in the string or cut out characters in particular places.


Python Strip Function and Relatives

String objects in Python have a "strip" method that can be used to remove characters from the beginning or end of a string. By default, strip removes whitespace from either end of a string. This can be useful if you're reading in from a file and want to remove line endings or padding in a line.

Video of the Day

If you want to remove other characters, pass a string as an argument to strip. Every character in the argument is removed from the beginning or end of the string if it appears there.


Python also provides string methods called "lstrip" and "rstrip." These function the same as the ordinary strip function, except they only remove characters from the left or the right ends of the string, respectively.

Note that the strip methods don't modify the original string. They return a copy of the string with the characters removed.

Python String Manipulation

There are other ways to remove characters from a Python string. The "replace" method returns a copy of a string with a particular substring replaced with a second provided substring. To replace a substring with nothing at all, make the second argument the empty string.


For example, "this is an example".replace('is an', ' ') returns the string "this example".

For more complex string manipulation, you may want to consider the built-in regular expression library "re." The "sub" function in the library allows you to express a substring matching a given expression with another string, including references to the original string or simply the empty string.

You can use a variant of "sub" called "subn" that also tells you how many substitutions were made.


Study the Python regular expression documentation to make sure you understand the regular expression sublanguage.

String Slices and Substrings

You can extract particular substrings of a string using the slice operator, similar to a Python list.

This allows you to extract portions of a string at certain positions. Use the square bracket operators for slices, with the syntax s[i] to extract the character of a string at position i, s[i:j] to extract the substring from position i to j-1 or s[i:j:step] to extract every "step" letter from position i to j-1. Indexes start at zero, not one.

Use negative indexes to slice from the right of the string rather than the left. For example, s[-1] is the last character in the string.