简体   繁体   中英

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

I have an assignment for which my script should be able to receive a string for input (eg 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

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

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

Disclaimer - even OP has opt out the regex, but this is just for a reference. (to show how much easier to approach this type of puzzle - which should be t he way to go)

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]

string='c27bdj3jddj45g'

lst=[]

for i in string:

if i.isdigit():
    lst.append(i)
else:
    lst.append('$')
print([int(i) for i in ''.join(lst).split('$') if i.isdigit()])

You can try this

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

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM