'error 'int' object is not subscriptable - python

im new in programming, i was trying simple code rle decompress, but im get error 'int' object is not subscriptable in if (JumlahKarakter[i].isalpha() == True): , how to fix this error?

this my code

TeksAsli = input("Masukan Input Teks Yan Akan Dikompress: ")
JumlahKarakter = len(TeksAsli)
Teks = ""
for i in range(0, JumlahKarakter):
    if (JumlahKarakter[i].isalpha() == True):
        for j in range(0,JumlahKarakter[i+1]):
            Teks = Teks + TeksAsli[i]

print("Hasil Decompress = ", Teks)


Solution 1:[1]

import re

TeksAsli = input("Masukan Input Teks Yan Akan Dikompress: ")
try:
    find_num = int(re.findall(r'\d+', TeksAsli)[0])
    find_text = re.sub("(\d+)", "", TeksAsli)
    Teks = ""
    for i in range(find_num):
        Teks += find_text
    print(Teks)
except IndexError:
    print("Error")

Solution 2:[2]

What you are basically trying to do in this code is you are subscripting the length of the input you have taken (i.e len(TeksAsli) which is stored in TeksAsli JumlahKarakter). This will surely return an error because for example if the length is 1. You are doing something like 1[1] which makes no sense. Secondly, in python, you do not require () parentheses to define if statement conditions. Third, you do not need to check in an if statement if the value is a bool, because if it is true it will automatically run the if statement. Here's what you can do:

TeksAsli = input("Masukan Input Teks Yan Akan Dikompress: ")
JumlahKarakter = len(TeksAsli)
Teks = ""
for i in range(0, JumlahKarakter):
    if TeksAsli[i].isalpha():
        Teks += TeksAsli[i]

print("Hasil Decompress = ", Teks)

I've removed some small errors or not needed code to improvise it. However, this above code is correct but there is a more efficient way of doing it which is:

TeksAsli = input("Masukan Input Teks Yan Akan Dikompress: ")
final = ''.join(TeksAsli.split(' ')) #Splits the string into list wherever space found. Then joins it without any spaces
print(final)

Both the programs work perfect, but the second one is more efficient and doesn't require a lot of variables.

Solution 3:[3]

Since len() returns an integer, stopping value of the range() needs to be JumlahKarakter instead.
I mean

for j in range(0,JumlahKarakter[i+1]): 

This needs to be like this

for j in range(0,JumlahKarakter):

And the same goes to if statement.

Btw, Looks like you're trying to do something like this

text = input()
alpha = []
nums = []
for i in text:
    if i.isalpha():
        alpha.append(i)
    else:
        nums.append(i)
for j in range(len(alpha)):
    print(alpha[j]*int(nums[j]),end="")

You can also do it like this

text = input()
for i in range(0,len(text),2):
    print(text[i]*int(text[i+1]),end="")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 The Myth
Solution 3