Skip to content Skip to sidebar Skip to footer

Remove Everything Before Space Using Regular Expression In Python

Suppose I have a string: 997 668, now I need to remove anything before space i.e I need 668 as the output. I need a solution using regular expression. Now I am using the below: x =

Solution 1:

Instead of getting the first of one item or the second of two items, simply get the last item with [-1]:

>>> '996 668'.split()[-1]
'668'
>>> '668'.split()[-1]
'668'

Solution 2:

Your own code would work if you were a bit more defensive

try:
   x = '997 668'
   x  = x.split(' ')[1]
except IndexError:
   x = x[0]

Solution 3:

If your input has multiple spaces, such as

235 989 877

then your question is somewhat ambiguous because you don't say whether you want to remove everything before the first space or everything before the last space.

TigerhawkT3's answer removes everything before the last space.

If you want to remove everything before the first space, you need the second parameter to split and do it this way:

>>> '996 668'.split(' ', 1)[-1]
'668'
>>> '996'.split(' ', 1)[-1]
'996'
>>> '996 351 980 221'.split(' ', 1)[-1]
'351 980 221'

Note that TigerhawkT3's answer (which is great, by the way) gives you the answer under the other interpretation:

>>> '996 351 980 221'.split()[-1]
'221'

Depends on what you want.

Just don't use a regex. :)

Solution 4:

Regex solution:

import re
re.findall('\d+', x)[-1]

re.findall always returns a list so you can avoid your IndexError without using an exception catcher.

Post a Comment for "Remove Everything Before Space Using Regular Expression In Python"