Home > other >  How to extract numbers from a string that has no spaces into a list
How to extract numbers from a string that has no spaces into a list

Time:12-26

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 very simple methods such as split, count, 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

CodePudding user response:

s='c27bdj3jddj45g'
lst=[]
for x in s:
    if x.isdigit():
        lst.append(x)
    else:
        lst.append('$')  # here $ is appended as a place holder so that all the numbers can come togetrher

Now, lst becomes :

#['$', '2', '7', '$', '$', '$', '3', '$', '$', '$', '$', '4', '5', '$']

''.join(lst).split('$') becomes:

['', '27', '', '', '3', '', '', '', '45', '']

Finally doing list comprehension to extract the numbers:

[x for x in ''.join(lst).split('$') if x.isdigit()]
['27', '3', '45']

CodePudding user response:

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 = 'c27bdj3jddj45g'
prv = ''
res = []
for c in s:
    if c.isdigit():
        prv  = c
    else:
        if prv != '': res.append(prv)
        prv = ''
print(res)

Output:

['27', '3', '45']

CodePudding user response:

You could try to use regex - re lib like this:

s = 'c27bdj3jddj45g'

import re

list(re.findall(r'\d ', s))     #  matching one more digits
['27', '3', '45']

# or to get *integer*
list(map(int, re.findall(r'\d ', s)))
[27, 3, 45]

CodePudding user response:

You can try this

print("".join([c if c.isdigit() else " " for c in "c27bdj3jddj45g"]).split())

Output:

['27', '3', '45']
  • Related