-1

Why isn't the initial whitespace being removed in this example?

s = ' Spain'
s = s.replace('\s*', '')
In[1]:s
Out[1]: ' Spain'

I noticed this when I was removing whitespaces from a series using pandas .str.replace, so I tried in this simple example and did not understand why this does not work.

Manic
  • 41
  • 5

2 Answers2

2
>>> s = ' Spain'
>>>
>>> # Regex
>>> re.sub('\s*', '', s)
'Spain'
>>>
>>> # str.lstrip
>>> s.lstrip()
'Spain'
>>>
Işık Kaplan
  • 2,815
  • 2
  • 13
  • 28
2
  • If you need to remove spaces only, use
s = s.replace(' ', '')

Note: replace does not work with regexes.

  • If you need to remove whitespace characters only from the beginning and the end, use
s = s.strip()
  • If you need to eliminate all of the whitespace characters (spaces, tabs, newlines), you can use
s = ''.join(s.split())
asikorski
  • 882
  • 6
  • 20