我正在编写代码,但看不到我在做错什么。我不断收到此错误'ValueError:int()的无效文字,基数为10:'2a'

时间:2019-10-16 11:07:18

标签: python

def EnterRLE():
    Data=[]
    AmountOfLines = int(input("How many lines of RLE compressed data do you want to enter? "))
    if AmountOfLines >= 3:
        Lines = 1
        while Lines <= AmountOfLines:
            Data.append(input("Please enter the compressed data one line at a time: "))
            Lines=Lines+1


        for index in range (0,AmountOfLines):
            SubStr = Data[index]


            index=0

            for index in range (0,len(SubStr)):
                number = int(SubStr[index:index+2])
                character = SubStr[index+2]
                print ("numberpart is: ", number)
                print ("character is :", character)
                print (number*character)


EnterRLE()

3 个答案:

答案 0 :(得分:0)

您没有提供足够的信息,所以我假设您在字符串中总是1位数字,后跟1个字符。

如果您的字符串SubStr'2a'开头,而index0,那么SubStr[index:index+2]会给您'2a',但这不能转换为整数。

如果字符串中的2位数字后跟1个字符,则会出现另一个问题。如果您的字符串SubStr'22a'开头,而index1,那么SubStr[index:index+2]将再次给您'2a'。您将不得不增加遍历字符串的步骤。

我重写了代码以使其更具Python风格,同时假定您在字符串中始终有1位数字后跟1个字符。修正2位数字很容易。

def enter_rle():
    amount_of_lines = int(
        input("How many lines of RLE compressed data do you want to enter? "))
    if amount_of_lines < 3:
        return

    data = []
    for _ in range(amount_of_lines):
        data.append(input("Please enter the compressed data one line at a time: "))

    for line in data:
        for index in range(0, len(line), 2):
            number = int(line[index])
            character = line[index + 1]
            print(f'numberpart is: {number}')
            print(f'character is : {character}')
            print(character * number)


enter_rle()

答案 1 :(得分:0)

  

我正在编写代码,但是我看不到自己在做错什么。

您做错了什么,是在2a提示时输入input("How many lines of RLE compressed data do you want to enter? "),然后将输入的字符串未经验证地传递给int()

答案 2 :(得分:0)

因此,如果我正确理解了您输入的一行,其格式如下:

[2 digit number][1 char][2 digit number][1 char] ...

一个块由3个字符组成,因此您希望您的index每轮增加3个。为此,您可以像这样修复for循环:

            for index in range (0, len(SubStr), 3):