I have an assignment for which my script should be able to receive a string for input (e.g. "c27bdj3jddj45g"
) and extract the numbers into a list (not just the digits, it should be able to detect full numbers).
I am not allowed to use regex at all, only simple methods like split, count and append.
Any ideas? (Using python)
Example for the output needed for the string I gave as an example:
['27','3', '45']
Nothing I have tried so far is worth mentioning here, I am pretty lost on which approach to take here without re.findall
, which I cannot use.
You can do this with a for-loop
and save the numbers
. Then, when you see no digit, append digits and reset the string.
s = 'g38ff11'
prv = ''
res = []
for c in s:
if c.isdigit():
prv += c
else:
if prv != '': res.append(prv)
prv = ''
if prv != '': res.append(prv)
print(res)
Output:
['38', '11']
You can also write a lambda to check and append:
s = 'g38ff11'
prv = ''
res = []
append_dgt = lambda prv, res: res.append(prv) if prv!="" else None
for c in s:
if c.isdigit():
prv += c
else:
append_dgt(prv, res)
prv = ''
append_dgt(prv, res)
print(res)