-2
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"

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
Haider Ali
  • 47
  • 7
  • This might be helpful later: `s = " extra spaces "; s2 = ' '.join(s.split())` s2 would be "extra spaces". Although, not shown here s has multiple spaces at the ends and middle. – cppxor2arr Feb 01 '18 at 10:18

4 Answers4

5
  1. paste your code instead of a screenshot
  2. Don't use a regex, but .strip() which removes all whitespaces from the beginning and end:
data = data.strip()
Zac G
  • 77
  • 6
FlyingTeller
  • 13,811
  • 2
  • 31
  • 45
3

You don't need Regex for that. Just use

"    abc   ".strip()

or

data = data.strip()
Greaka
  • 710
  • 10
  • 16
3

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

sid8491
  • 6,247
  • 4
  • 32
  • 58
2

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
Steffi Keran Rani J
  • 3,051
  • 3
  • 25
  • 47