Search code examples
pythonlistmultiplication

How can the different elements of the list be multiplied (str and int)?


I am trying to get conversion of string like 'a3b4' to 'aaabbbb'. How can this be done without additional modules? So far my code looks like this:

s = 'a3b4'
n = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
a = []
b = []

for i in range(len(s)):
    if s[i] in n:
        a.append(s[i])
    if s[i] not in n:
        b.append(s[i])
for i in range(len(b)):
    print(b[i])

Solution

  • This should work:

    letters = list(s[::2])
    nums = list(s[1::2])
    res = ''.join([a*int(b) for a,b in zip(letters,nums)])
    
    >>res
    Out[1]: 'aaabbbb'
    

    EDIT:

    If you want to match any srting and any digits you should use regex:

    letters = re.findall(r'[a-z]+',s)
    nums = re.findall(r'\d+',s)
    res = ''.join([a*int(b) for a,b in zip(letters,nums)])
    

    for:

     s='a10b3'
    

    output is:

    >>res
    Out[2]: 'aaaaaaaaaabbb'