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

发布于 2025-01-14 22:14:08 字数 406 浏览 3 评论 0原文

如果我输入A9输出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)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱人如己 2025-01-21 22:14:08

这里不需要一个循环(或两个循环!)。

只需将字符串相乘:

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

输出:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文