Strip whitespace
There are various ways to remove spaces from a string in Python. This tutorial is aimed to provide a short example of various functions you can use to remove whitespaces from a string.
Create Text
# Create text
text_data = [' Be yourself; everyone else is already taken ', ' So many books, so little time.', ' You only live once ']
Remove Whitespace
# Strip whitespaces
strip_whitespace = [string.strip() for string in text_data]
# Show text
strip_whitespace
Output:
[' Be yourself; everyone else is already taken ', ' So many books, so little time. ', ' You only live once ']
How to Remove Extra Space Between Text in Python (re.sub Operation)
So far, we have used only functions of the strip-family. However, to get rid of duplicate blank characters between the words of our sentence we need to apply the re.sub operation: https://docs.python.org/2/library/re.html
import re Import regular expressions
string = re.sub(" +", " ",my_string) # Apply sub function
print(string) # Print updated string |
# " This sentence contains many redundant whitespaces ! "