Remove Space
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.
objective:
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):
lstrip() function in the above example strips the leading space so the output will be
Remove Space at the end of the string in Python (Strip trailing space in python):
rstrip() function in the above example strips the trailing space so the output will be
Remove Space at the Start and end of the string in Python (Strip trailing and trailing space in python):
strip() function in the above example strips, both leading and trailing space so the output will be
Remove or strip all the spaces in python:
The above example removes all the spaces in python. So the output will be
Remove or strip the duplicated space in python:
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.
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
so the resultant output will be
Sou
Last updated