Liz Liz - 1 month ago 4x
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
which works, but how do I make it work without knowing the number of digits?


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

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

Another way is with index or find:

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

And another way with re:

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

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])

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