- Remove Space in Python – (strip Leading, Trailing, Duplicate spaces in string)
- Remove Space at the start of the string in Python (Strip leading space in python):
- Remove Space at the end of the string in Python (Strip trailing space in python):
- Remove Space at the Start and end of the string in Python (Strip trailing and trailing space in python):
- Remove or strip all the spaces in python:
- Remove or strip the duplicated space in python:
- Using Regular Expression to trim spaces:
- Author
- Related Posts:
- How To Remove Spaces from a String In Python
- Remove Leading and Trailing Spaces Using the strip() Method
- Remove All Spaces Using the replace() Method
- Remove Duplicate Spaces and Newline Characters Using the join() and split() Methods
- Remove All Spaces and Newline Characters Using the translate() Method
- Remove Whitespace Characters Using Regex
- Conclusion
- Trim a String in Python – How to Strip Trailing Whitespace
- How To Trim Whitespace From A String in Python
- How to Remove Only Any Trailing Whitespace in Python
- Conclusion
Remove Space in Python – (strip Leading, Trailing, Duplicate spaces in string)
Remove space in python string / strip space in python string : In this Tutorial we will learn how to remove or strip leading , trailing and duplicate spaces in python with lstrip() , rstrip() and strip() Function with an example for each . lstrip() and rstrip() function trims the left and right space respectively. strip() function trims all the white space.
- Remove (strip) space at the start of the string in Python – trim leading space
- Remove (strip) space at the end of the string in Python – trim trailing space
- Remove (strip) white spaces from start and end of the string – trim space.
- Remove all the spaces in python
- Remove Duplicate Spaces in Python
- Trim space in python using regular expressions.
Let’s see the example on how to Remove space in python string / strip space in python string one by one.
Remove Space at the start of the string in Python (Strip leading space in python):
## Remove the Starting Spaces in Python string1=" This is Test String to strip leading space" print (string1) print (string1.lstrip())
lstrip() function in the above example strips the leading space so the output will be
‘ This is Test String to strip leading space’
‘This is Test String to strip leading space’
Remove Space at the end of the string in Python (Strip trailing space in python):
## Remove the Trailing or End Spaces in Python string2="This is Test String to strip trailing space " print (string2) print (string2.rstrip())
rstrip() function in the above example strips the trailing space so the output will be
‘This is Test String to strip trailing space ‘
‘This is Test String to strip trailing space’
Remove Space at the Start and end of the string in Python (Strip trailing and trailing space in python):
## Remove the whiteSpaces from Beginning and end of the string in Python string3=" This is Test String to strip leading and trailing space " print (string3) print (string3.strip())
strip() function in the above example strips, both leading and trailing space so the output will be
‘ This is Test String to strip leading and trailing space ‘
‘This is Test String to test leading and trailing space’
Remove or strip all the spaces in python:
## Remove all the spaces in python string4=" This is Test String to test all the spaces " print (string4) print (string4.replace(" ", ""))
The above example removes all the spaces in python. So the output will be
‘ This is Test String to test all the spaces ‘
‘ThisisTestStringtotestallthespaces’
Remove or strip the duplicated space in python:
# Remove the duplicated space in python import re string4=" This is Test String to test duplicate spaces " print (string4) print (re.sub(' +', ' ',string4))
- We will be using regular expression to remove the unnecessary duplicate spaces in python.
- sub() function: re.sub() function takes the string4 argument and replaces one or more space with single space as shown above so the output will be.
‘ This is Test String to test duplicate spaces ‘
‘ This is Test String to test duplicate spaces ‘
Using Regular Expression to trim spaces:
re.sub() function takes the string1 argument and apply regular expression to trim the white spaces as shown below
string1 = " This is to test space " print('Remove all space:',re.sub(r"\s+", "", string1), sep='') # trims all white spaces print('Remove leading space:', re.sub(r"^\s+", "", string1), sep='') # trims left space print('Remove trailing spaces:', re.sub(r"\s+$", "", string1), sep='') # trims right space print('Remove leading and trailing spaces:', re.sub(r"^\s+|\s+$", "", string1), sep='') # trims both
so the resultant output will be
Remove all space:’Thisistotestspace’
Remove leading space:’This is to test space ‘
Remove trailing spaces:’ This is to test space’
Remove leading and trailing spaces:’This is to test space’
Author
With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark. View all posts
Related Posts:
How To Remove Spaces from a String In Python
This tutorial provides examples of various methods you can use to remove whitespace from a string in Python.
A Python String is immutable, so you can’t change its value. Any method that manipulates a string value returns a new string.
The examples in this tutorial use the Python interactive console in the command line to demonstrate different methods that remove spaces. The examples use the following string:
s = ' Hello World From DigitalOcean \t\n\r\tHi There '
Output Hello World From DigitalOcean Hi There
This string has different types of whitespace and newline characters, such as space ( ), tab ( \t ), newline ( \n ), and carriage return ( \r ).
Remove Leading and Trailing Spaces Using the strip() Method
The Python String strip() method removes leading and trailing characters from a string. The default character to remove is space.
Declare the string variable:
Use the strip() method to remove the leading and trailing whitespace:
Output'Hello World From DigitalOcean \t\n\r\tHi There'
If you want to remove only the leading spaces or trailing spaces, then you can use the lstrip() and rstrip() methods.
Remove All Spaces Using the replace() Method
You can use the replace() method to remove all the whitespace characters from the string, including from between words.
Declare the string variable:
Use the replace() method to replace spaces with an empty string:
Output'HelloWorldFromDigitalOcean\t\n\r\tHiThere'
Remove Duplicate Spaces and Newline Characters Using the join() and split() Methods
You can remove all of the duplicate whitespace and newline characters by using the join() method with the split() method. In this example, the split() method breaks up the string into a list, using the default separator of any whitespace character. Then, the join() method joins the list back into one string with a single space ( » » ) between each word.
Declare the string variable:
Use the join() and split() methods together to remove duplicate spaces and newline characters:
Output'Hello World From DigitalOcean Hi There'
Remove All Spaces and Newline Characters Using the translate() Method
You can remove all of the whitespace and newline characters using the translate() method. The translate() method replaces specified characters with characters defined in a dictionary or mapping table. The following example uses a custom dictionary with the string.whitespace string constant, which contains all the whitespace characters. The custom dictionary replaces all the characters in string.whitespace with None .
Import the string module so that you can use string.whitespace :
Declare the string variable:
Use the translate() method to remove all whitespace characters:
Output'HelloWorldFromDigitalOceanHiThere'
Remove Whitespace Characters Using Regex
You can also use a regular expression to match whitespace characters and remove them using the re.sub() function.
This example uses the following file, regexspaces.py , to show some ways you can use regex to remove whitespace characters:
import re s = ' Hello World From DigitalOcean \t\n\r\tHi There ' print('Remove all spaces using regex:\n', re.sub(r"\s+", "", s), sep='') # \s matches all white spaces print('Remove leading spaces using regex:\n', re.sub(r"^\s+", "", s), sep='') # ^ matches start print('Remove trailing spaces using regex:\n', re.sub(r"\s+$", "", s), sep='') # $ matches end print('Remove leading and trailing spaces using regex:\n', re.sub(r"^\s+|\s+$", "", s), sep='') # | for OR condition
Run the file from the command line:
You get the following output:
Remove all spaces using regex: HelloWorldFromDigitalOceanHiThere Remove leading spaces using regex: Hello World From DigitalOcean Hi There Remove trailing spaces using regex: Hello World From DigitalOcean Hi There Remove leading and trailing spaces using regex: Hello World From DigitalOcean Hi There
Conclusion
In this tutorial, you learned some of the methods you can use to remove whitespace characters from strings in Python. Continue your learning about Python strings.
Want to deploy your application quickly? Try Cloudways, the #1 managed hosting provider for small-to-medium businesses, agencies, and developers — for free. DigitalOcean and Cloudways together will give you a reliable, scalable, and hassle-free managed hosting experience with anytime support that makes all your hosting worries a thing of the past. Start with $100 in free credits!
Trim a String in Python – How to Strip Trailing Whitespace
Dionysia Lemonaki
Python has three built-in methods for trimming leading and trailing whitespace and characters from strings: strip() , lstrip() , and rstrip() .
In this article, I will explain how to remove trailing whitespace in Python using the rstrip() method.
How To Trim Whitespace From A String in Python
To trim a string and remove any whitespace, whether leading or trailing, use the strip() method.
When the strip() method has no argument, it removes both leading and trailing whitespace from a string.
So, if you have whitespace at the start or end of a word or phrase, strip() alone, by default, will remove it.
Let’s take the following example:
fave_phrase = " Hello World "
I stored the phrase » Hello World » in a variable named fave_phrase .
The phrase has leading whitespace — a space before the first character, H .
The phrase also has trailing whitespace — a space after the last character, d .
I then print the contents of fave_phrase to the console:
print(fave_phrase) # output Hello World
To remove both leading and trailing whitespace from the phrase, call the strip() method on fave_phrase and store the result in the variable with the name trimmed_fave_phrase like so:
fave_phrase = " Hello World " trimmed_fave_phrase = fave_phrase.strip() print(trimmed_fave_phrase) # output Hello World
Now any whitespace at the beginning and end of the string has gone!
How to Remove Only Any Trailing Whitespace in Python
But what if you want to remove only trailing whitespace (that is, any whitespace at the end of the string)?
Python has the rstrip() method you can use to do just that:
fave_phrase = " Hello World " trimmed_fave_phrase = fave_phrase.rstrip() print(trimmed_fave_phrase) # output Hello World
In the example above, the leading space at the beginning of the string remains preserved, and the trailing space gets removed.
So, with rstrip() , the whitespace gets removed only from the end of the string.
Conclusion
And there you have it! You now know how to strip any trailing whitespace from a string in Python.
Thanks for reading, and happy coding!
Dionysia Lemonaki
If this article was helpful, tweet it .
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.