IndexError: string index out of range in RLE python

69 views Asked by At

if i input A9 output AAAAAAAAA but i input A10 program will be error index out of range. how to fix the program when im input A10 or above the program is workly. This my code

Char = input ("Input Char : ")
Total = len(Char)
Decompress =""

for i in range (0, Total,2):
    Loop = int(Char[i+1])
    for j in range (0, Loop):
        Decompress = Decompress + Char [i]
        
print("Output : ",Decompress)
1

There are 1 answers

4
mozway On

You don't need a loop (or two loops!) here.

Simply multiply the string:

Char = input("Input Char : ")
print("Output : ", Char[0]*int(Char[1:]))

output:

Input Char : A15
Output :  AAAAAAAAAAAAAAA

more generic input

assuming you want to handle repeated pairs of char(s)/digits, this is quite easy to achieve with a regex:

import re

Char = input ("Input Char : ")
print("Output : ", ''.join(c*int(n) for c,n in re.findall('(\D+)(\d+)', Char)))

example:

Input Char : A2B10CD3
Output : AABBBBBBBBBBCDCDCD