Liz Liz - 2 months ago 6
Python Question

Extract a number from a string, after a certain character

Ayyyy, I need some help. I have the following strings, always in "char,num" format:

s = "abcdef,12"
v = "gbhjjj,699"


I want to get just the digits after the comma, how do I do that without splitting the string with the comma as a delimiter?

I tried
s[-2:]
and
v[-3:]
which works, but how do I make it work without knowing the number of digits?

Answer

Using split is superior because it is very clear and fast:

>>> s = "abcdef,12"
>>> s.split(',')[1]
'12'

Another way is with index or find:

>>> s = "abcdef,12"
>>> s[s.find(',')+1:]
'12'

And another way with re:

>>> import re
>>> s = "abcdef,12"
>>> re.search(r',(.*)', s).group(1)
'12'

And with csv (and io so I don't have to write a file to the hard drive):

>>> import csv
>>> import io
>>> s = "abcdef,12"
>>> r = csv.reader(i)
>>> for line in r:
...     print(line[1])
...
12

I'm sure there are other ways to accomplish this task. This is just a small sample.