str 与 int 关联的数组字段存在无效 int 错误

问题描述 投票:0回答:1

我不断收到此错误:ValueError:以 10 为基数的 int() 的文字无效:

if __name__ == '__main__':
    try:
        def encrypt(file):
            encrypt = " "
            with open("test.txt","r") as f:
                lines = f.readlines()
                for i in range(0, len(lines), 2):
                    count = int((lines[i]))
                    word = lines[i + 1].strip()
                    encrypt += word[:count] + " "
            return encrypt.strip()
    except Exception as e:
        print(e)
    finally:
        print(" ")
        encrypted_string = encrypt("test.txt")
        print(encrypted_string)

        [print("hello world")]

我知道这个错误意味着与 int 关联的字符串可以被解析。我该如何解决它?

python arrays
1个回答
0
投票

问题是您尝试将文件中的每一行转换为整数,但某些行可能不包含有效的整数。

您可以使用字符串的

isdigit()
方法,如果字符串仅由数字组成,则返回 True。

if __name__ == '__main__':
try:
    def encrypt(file):
        encrypt = ""
        with open("test.txt","r") as f:
            lines = f.readlines()
            for i in range(0, len(lines), 2):
                if lines[i].strip().isdigit():  # Check if the line contains a valid integer
                    count = int(lines[i].strip())
                    word = lines[i + 1].strip()
                    encrypt += word[:count] + " "
                else:
                    print(f"Warning: Invalid integer found on line {i + 1}: {lines[i]}")
        return encrypt.strip()
except Exception as e:
    print(e)
finally:
    print(" ")
    encrypted_string = encrypt("test.txt")
    print(encrypted_string)

    [print("hello world")]
© www.soinside.com 2019 - 2024. All rights reserved.