-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
  • 607,720
  • 39
  • 448
  • 563
Haider Ali
  • 47
  • 1
  • 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
  • 7
FlyingTeller
  • 17,638
  • 3
  • 38
  • 53
3

You don't need Regex for that. Just use

"    abc   ".strip()

or

data = data.strip()
Greaka
  • 735
  • 7
  • 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,622
  • 6
  • 38
  • 64
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,667
  • 4
  • 34
  • 56