Python (Scripting) - Remove whitespace using strip, lstrip and rstrip

by
Jeremy Canfield |
Updated: April 15 2024
| Python (Scripting) articles
strip can be used to remove whitespace. Take for example this script.
#!/usr/bin/python
foo = " Hello World "
print("'"+foo+"'")
The following should be printed, showing whitespace to the left and right.
' Hello World '
Here is how strip can be used.
#!/usr/bin/python
foo = " Hello World "
foo = foo.strip()
print("'"+foo+"'")
Should produce the following, with the whitespace to the left and right removed.
'Hello World'
Or lstrip, to only remove whitespace to the left.
#!/usr/bin/python
foo = " Hello World "
foo = foo.lstrip()
print("'"+foo+"'")
Which should print the following.
'Hello World '
Or rstrip, to only remove whitespace to the right.
#!/usr/bin/python
foo = " Hello World "
foo = foo.rstrip()
print("'"+foo+"'")
Which should print the following.
' Hello World'
If you want to remove whitespace in a string, re.sub can be used, for example, to update a phone number to have no whitespace.
#!/usr/bin/python3
import re
phone = "1(414) 744 0107"
phone = phone.strip()
phone = re.sub('\s', '', phone)
phone = re.sub('\(', '', phone)
phone = re.sub('\)', '', phone)
Did you find this article helpful?
If so, consider buying me a coffee over at