Skip to main content

How to Remove Spaces and Line Breaks from Both Ends of a String in Python with strip

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

Text from files and commands often comes with extra spaces or a line break at the end, which you can't see but which break comparisons. str.strip() removes them from both ends. This guide cleans up a commit hash as a command prints it, with real output from Python 3.15.2.

Syntax​

Syntax
<text>.strip()
PartWhat it means
<text>Any string
.strip()Returns a new string without the whitespace at the start and the end. The text in between stays as it is

Python's reference: "Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace."

Prerequisites​

  • uv and Python. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

line is a commit hash with two spaces before it and a line break after it, the way text often arrives. repr prints a string with its quotes and with \n for the line break, so the invisible characters show:

strip_text.py
line = " 6740b92\n"
print(repr(line))
print(repr(line.strip()))

The strip_text.py script in a macOS-style code window: line holds two spaces, 6740b92 and a newline, then it prints the repr of line and of line.strip().

Step 2: Run It​

Terminal
uv run python strip_text.py
Output
' 6740b92\n'
'6740b92'

The script's output in a terminal: '  6740b92\n' and then '6740b92'.

strip() removed the two spaces in front and the line break at the end.

Common Mistakes​

MistakeWhat happensDo this instead
Calling line.strip() without keeping the resultStrings can't change, so line stays as it was: it still printed ' 6740b92\n'Save it: line = line.strip()

Troubleshooting​

SymptomLikely causeFix
Two strings print the same but == says they differOne has whitespace at an endCompare a.strip() == b.strip(), and print with repr to see it

FAQ​

How do I remove only one side?​

lstrip() removes the start and rstrip() the end; strip() does both.

Can I remove other characters?​

Yes: pass them as a string, such as strip("/"); with nothing passed, strip() removes whitespace.

Conclusion​

" 6740b92\n".strip() returned '6740b92', without the leading spaces and the trailing line break. Save the result, because the original string doesn't change.

Additional Resources​

  • str.strip — strip, and the chars argument.