簡體   English   中英

IndexError:RLE 中的字符串索引超出范圍 python

[英]IndexError: string index out of range in RLE python

如果我輸入A9 output AAAAAAAAA但我輸入A10程序將出現錯誤索引超出范圍。 當我輸入A10或以上程序正常時如何修復程序。 這是我的代碼

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)

您在這里不需要一個循環(或兩個循環)。

簡單地乘以字符串:

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

output:

Input Char : A15
Output :  AAAAAAAAAAAAAAA

更通用的輸入

假設你想處理重復的字符/數字對,這很容易用正則表達式實現:

import re

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

例子:

Input Char : A2B10CD3
Output : AABBBBBBBBBBCDCDCD

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM