ZetCode

Python strip string

last modified November 19, 2026 Python 3.15

In this article we show how to strip strings in Python.

Stripping removes unwanted characters from the beginning and the end of a string. Other languages call this operation trimming. Python strings have three stripping methods and two methods for removing a fixed prefix or suffix:

Strings are immutable; all these methods return a new string and leave the original unchanged.

The strip method

Without arguments, strip removes all leading and trailing whitespace.

strip_simple.py
word = '   falcon \n'

cleaned = word.strip()

print(repr(word))
print(repr(cleaned))
print(len(word), len(cleaned))

We strip a word surrounded by spaces and a newline. The repr function shows the invisible characters, so we can see what has been removed.

$ python strip_simple.py
'   falcon \n'
'falcon'
11 6

Stripping one side

The lstrip method strips only the start of the string and rstrip only its end.

strip_sides.py
line = '\t  sky blue  \n'

print(repr(line.lstrip()))
print(repr(line.rstrip()))
print(repr(line.strip()))

The line starts with a tab and two spaces and ends with two spaces and a newline. Each method leaves the other side untouched. Whitespace inside the string, here the space between sky and blue, is never removed.

$ python strip_sides.py
'sky blue  \n'
'\t  sky blue'
'sky blue'

What counts as whitespace

The methods without arguments strip every character for which isspace returns True. This includes Unicode spaces, not only ASCII ones.

whitespace_chars.py
samples = {
    'space': ' ',
    'tab': '\t',
    'newline': '\n',
    'carriage return': '\r',
    'form feed': '\f',
    'no-break space': '\u00a0',
    'ideographic space': '\u3000',
    'zero-width space': '\u200b',
    'BOM': '\ufeff',
}

for name, ch in samples.items():
    text = f'{ch}word{ch}'
    print(f'{name:18} isspace={ch.isspace()!s:5} -> {text.strip()!r}')

We put each character on both sides of a word and strip it. The no-break space and the ideographic space used in East Asian text are whitespace. The zero-width space and the byte order mark (BOM) are not, so they survive strip. Both often come from text copied from web pages or from files saved by Windows editors; we have to remove them explicitly, for instance with strip('\ufeff').

$ python whitespace_chars.py
space              isspace=True  -> 'word'
tab                isspace=True  -> 'word'
newline            isspace=True  -> 'word'
carriage return    isspace=True  -> 'word'
form feed          isspace=True  -> 'word'
no-break space     isspace=True  -> 'word'
ideographic space  isspace=True  -> 'word'
zero-width space   isspace=False -> '\u200bword\u200b'
BOM                isspace=False -> '\ufeffword\ufeff'

Stripping given characters

All three methods accept an optional chars argument. It is not a prefix or a suffix; it is a set of characters. The method removes characters from the end for as long as they belong to the set.

strip_chars.py
url = 'www.example.com'
print(url.strip('w.com'))

price = '$$$129.99$'
print(price.strip('$'))

row = '---+---title---+---'
print(row.strip('-+'))

print('xxyxyhelloyxyx'.strip('xy'))

In the first call, the set contains the letters w, c, o, m, and the dot. Stripping stops at the first character on each side that is not in the set. The order of the characters in the argument does not matter, as the last line shows.

$ python strip_chars.py
example
129.99
title
hello

A common mistake

Because chars is a set, rstrip is the wrong tool for cutting off a file extension.

strip_pitfall.py
files = ['report.txt', 'notes.txt', 'data.txt', 'test.txt']

for name in files:
    print(f'{name:12} rstrip: {name.rstrip(".txt")!r:10} '
          f'removesuffix: {name.removesuffix(".txt")!r}')

rstrip(".txt") removes the characters ., t, and x from the end in any order. For report.txt it also eats the final t of the name. The bug is easy to miss, because most names in a test list do not end in one of these letters. The removesuffix method removes exactly one .txt.

$ python strip_pitfall.py
report.txt   rstrip: 'repor'    removesuffix: 'report'
notes.txt    rstrip: 'notes'    removesuffix: 'notes'
data.txt     rstrip: 'data'     removesuffix: 'data'
test.txt     rstrip: 'tes'      removesuffix: 'test'

removeprefix and removesuffix

The removeprefix and removesuffix methods were added in Python 3.9. They remove the given substring once, and only if the string starts or ends with it.

remove_affix.py
names = ['test_parser', 'test_lexer', 'helper', 'test_test_utils']

for name in names:
    print(f'{name:16} -> {name.removeprefix("test_")}')

print()

url = 'https://example.com/'
print(url.removeprefix('https://').removesuffix('/'))
print('abc'.removesuffix('xyz'))

A string without the prefix is returned unchanged. In test_test_utils, only the first test_ is removed. The methods return strings, so the calls can be chained.

$ python remove_affix.py
test_parser      -> parser
test_lexer       -> lexer
helper           -> helper
test_test_utils  -> test_utils

example.com
abc

Whitespace inside a string

The stripping methods work only at the ends. To collapse runs of whitespace inside a string, we split and join it, or use a regular expression.

inner_spaces.py
import re

title = '   An   old\tsilent \n pond  '

print(repr(title.strip()))
print(repr(' '.join(title.split())))
print(repr(re.sub(r'\s+', ' ', title).strip()))

Without arguments, split splits on any run of whitespace and ignores whitespace at the ends, so ' '.join(title.split()) both strips and normalizes the string. The re.sub version replaces every run with a single space; we still have to strip the result, because the leading and trailing runs become single spaces.

$ python inner_spaces.py
'An   old\tsilent \n pond'
'An old silent pond'
'An old silent pond'

Cleaning user input

Input typed by users or read from forms often has stray spaces and newlines. We strip it before comparing.

form_fields.py
answers = ['  Yes', 'yes\n', ' YES ', 'no', '   ', 'Y']

for raw in answers:
    answer = raw.strip().casefold()

    if not answer:
        print(f'{raw!r:9} -> empty answer')
    elif answer in ('y', 'yes'):
        print(f'{raw!r:9} -> accepted')
    else:
        print(f'{raw!r:9} -> declined')

We strip each answer and then fold its case with casefold. An answer that consists only of whitespace becomes an empty string, which is false in a boolean context.

$ python form_fields.py
'  Yes'   -> accepted
'yes\n'   -> accepted
' YES '   -> accepted
'no'      -> declined
'   '     -> empty answer
'Y'       -> accepted

Stripping lines of a file

Lines read from a file keep their newline characters. The following file has trailing spaces, a trailing tab, indentation, and an empty line.

cities.txt
Bratislava   
  Budapest
Prague	

  Vienna  

We read the lines and clean them.

read_lines.py
from pathlib import Path

with Path('cities.txt').open(encoding='utf-8') as f:
    lines = f.readlines()

print(lines)

cities = [line.strip() for line in lines if line.strip()]
print(cities)

The readlines method keeps the \n at the end of each line. The list comprehension strips each line and drops lines that are empty after stripping. If the indentation matters, as in Python or YAML source, we use rstrip('\n') or rstrip() instead, which keep the leading spaces.

$ python read_lines.py
['Bratislava   \n', '  Budapest\n', 'Prague\t\n', '\n', '  Vienna  \n']
['Bratislava', 'Budapest', 'Prague', 'Vienna']

Trailing zeros

Stripping characters from a number formatted as a string needs a guard, because the characters we strip may also be significant.

trailing_zeros.py
def strip_zeros_naive(s):
    return s.rstrip('0').rstrip('.')


def strip_zeros(s):
    if '.' not in s:
        return s
    return s.rstrip('0').rstrip('.')


for value in ['3.1400', '2.000', '0.50', '100', '10.0']:
    print(f'{value:7} naive: {strip_zeros_naive(value):5} '
          f'fixed: {strip_zeros(value)}')

The naive version strips zeros and then the dot. It turns 100 into 1, because the zeros of an integer are significant. The fixed version strips only numbers that have a decimal point. For numbers rather than strings, the g format specifier or the normalize method of decimal.Decimal are other options.

$ python trailing_zeros.py
3.1400  naive: 3.14  fixed: 3.14
2.000   naive: 2     fixed: 2
0.50    naive: 0.5   fixed: 0.5
100     naive: 1     fixed: 100
10.0    naive: 10    fixed: 10

Stripping bytes

The bytes type has the same methods. The argument must be a bytes object too.

strip_bytes.py
record = b'falcon\x00\x00\x00\x00'
line = b'  GET /index.html HTTP/1.1\r\n'

print(record.rstrip(b'\x00'))
print(line.strip())

name = record.rstrip(b'\x00').decode('ascii')
print(name, len(name))

Fixed-width binary records are often padded with null bytes; we remove them with rstrip(b'\x00') before decoding. The strip method without arguments removes ASCII whitespace, including the \r\n line ending of a network protocol line.

$ python strip_bytes.py
b'falcon'
b'GET /index.html HTTP/1.1'
falcon 6

Parsing a settings file

In the last example we combine stripping with partition to read a simple settings file. The file has a comment, blank lines, spaces around the equals sign, an inline comment, a quoted value, and one invalid line.

settings.ini
# server settings
host = localhost   
port=8080

  debug = yes   # inline comment
name = "My App"
verbose

The parser strips each part separately.

read_settings.py
from pathlib import Path


def parse_settings(text):
    settings = {}

    for lineno, line in enumerate(text.splitlines(), start=1):
        line = line.partition('#')[0].strip()

        if not line:
            continue

        key, sep, value = line.partition('=')

        if not sep:
            print(f'line {lineno}: missing "=", skipped')
            continue

        settings[key.strip()] = value.strip().strip('"')

    return settings


text = Path('settings.ini').read_text(encoding='utf-8')

for key, value in parse_settings(text).items():
    print(f'{key!r}: {value!r}')

We cut off a comment with partition('#') and strip the rest; blank lines and comment lines become empty strings and are skipped. The second partition splits the line at the first equals sign. The key and the value are stripped separately, and strip('"') then removes the quotes of the value. The order matters: stripping the quotes before the spaces would leave them in place.

$ python read_settings.py
line 7: missing "=", skipped
'host': 'localhost'
'port': '8080'
'debug': 'yes'
'name': 'My App'

Source

str.strip – Python documentation

str.removeprefix – Python documentation

In this article we have stripped strings in Python with strip, lstrip, rstrip, removeprefix, and removesuffix. See also Python split string, Python replace string, Python join string, and Python string.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.