data = " Taylors Lakes, VIC "
I need regular expression to remove extra spaces from this string but not from between the words so that the string looks like this
data = "Taylors Lakes, VIC"
data = " Taylors Lakes, VIC "
I need regular expression to remove extra spaces from this string but not from between the words so that the string looks like this
data = "Taylors Lakes, VIC"
.strip()
which removes all whitespaces from the beginning and end:data = data.strip()
You can just use strip()
method, it will remove both beginning and ending whitespaces from the string.
data = " Taylors Lakes, VIC "
print(data.strip())
Output: Taylors Lakes, VIC
However if you still want to use regex, below code will do it:
import re
data = " Taylors Lakes, VIC "
data = re.sub('^[ \t]+|[ \t]+$', '', data)
print(data)
Output: Taylors Lakes, VIC
The solution in Python 3 is :
data = " Taylors Lakes, VIC "
print(data.strip())
The output is:
>>> Taylors Lakes, VIC
The solution in Python 2:
data = " Taylors Lakes, VIC "
print data.strip()
The output is:
>>> Taylors Lakes, VIC