Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to separate alternating digits and characters in string into dict or list?

‘L134e2t1C1o1d1e1’

the original string is "LeetCode"

but I need to separate strings from digits, digits can be not only single-digit but also 3-4 digits numbers like 345.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My code needs to separate into dict of key values; keys are characters and numbers is the digit right after the character. Also create 2 lists of separate digits, letters only.

expected output:

letters = ['L', 'e', 't', 'C', 'o', 'd', 'e']
digits = [134,2,1,1,1,1,1]

This code is not properly processing this.

def f(s):

    d = dict()
    letters = list()
    # letters = list(filter(lambda x: not x.isdigit(), s))

    i = 0
    while i < len(s):
        print('----------------------')
        if not s[i].isdigit():

            letters.append(s[i])

        else:
            j = i
            temp = ''
            while j < len(s) and s[j].isdigit():
                j += 1

            substr = s[i:j]
            print(substr)
            
        i += 1

    print('----END -')
    print(letters)

>Solution :

You edited your question and I got a bit confused, so here is a really exhaustive code giving you a list of letters, list of the numbers, the dict with the number associated with the number, and finally the sentence with corresponding number of characters …

def f(s):
    letters = [c for c in s if c.isalpha()]
    numbers = [c for c in s if c.isdigit()]

    mydict = {}
    currentKey = ""
    for c in s:
        print(c)
        if c.isalpha():
            mydict[c] = [] if c not in mydict.keys() else mydict[c]
            currentKey = c
        elif c.isdigit():
            mydict[currentKey].append(c)

    sentence = ""
    for i in range(len(letters)):
        count = int(numbers[i])
        while count > 0:
            sentence += letters[i]
            count -= 1

    print(letters)
    print(numbers)
    print(mydict)
    print(sentence)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading