Liz Liz - 1 year ago 68
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download