You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

读取文本筛选偶数时遇ValueError: invalid literal for int() with base 10: ''的解决方法

解决ValueError: invalid literal for int() with base 10: ''问题

这个错误的根源很明确:你用split(" ")按单个空格分割文本时,会产生空字符串(比如文本行末尾有空格,或者数字之间有多个空格),而int('')显然无法转换成整数,就触发了这个ValueError。

给你两种解决思路,推荐第一种:

方法一:使用无参数的split()(最优解)

Python的str.split()如果不带参数,会自动处理任意数量的空白字符(包括单个空格、多个空格、制表符甚至换行),同时还会忽略字符串首尾的空白,这样分割出来的列表里就不会有空字符串了。另外,建议用with语句来处理文件,这是Python操作文件的最佳实践,能自动帮你关闭文件:

with open('test.txt', 'r') as infile:
    content = infile.read()
    # 无参数split直接分割所有空白
    num_strings = content.split()
    for s in num_strings:
        num = int(s)
        if num % 2 == 0:
            print(s)

方法二:过滤空字符串(兼容原有split逻辑)

如果你一定要保留split(" ")的写法,可以在循环里先判断当前字符串是否为空,为空就跳过:

with open('test.txt', 'r') as infile:
    val = infile.read()
    val_list = val.split(" ")
    for i in val_list:
        # 跳过空字符串
        if not i:
            continue
        if int(i) % 2 == 0:
            print(i)

第一种方法更健壮,不管你的文本里是单个空格还是多个空格分隔数字,甚至行尾有多余空格,都能正确处理,所以优先推荐。

内容的提问来源于stack exchange,提问作者jasds

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:05:07