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

Python程序触发ValueError: invalid literal for int() with base 10: ''报错的原因咨询

Why does this ValueError occur when converting to int?

Let's break down exactly what's happening here.

Your error ValueError: invalid literal for int() with base 10: '' happens because you're trying to convert an empty string to an integer, and Python doesn't allow that—there's no numeric value to parse from an empty string.

Looking at your code:

t = int(input())
for _ in range(t):
    n = input()
    for i in range(len(n)):
        first = n[:i]
        second = n[i:]
        print(type(first))
        print(type(int(first)))

Here's the root cause:

  • When i starts at 0 (since range(len(n)) begins at 0), the slice n[:0] returns an empty string ('').
  • Calling int('') immediately triggers that ValueError because there's no valid numeric literal to convert.

For example, if you input 123 for n:

  • When i=0, first is '' (empty string), and int(first) fails right away.
  • The loop only works as expected when i is 1 or higher, because then n[:i] will contain at least one character from the input string.

If you want to fix this error, you have two simple options:

  1. Adjust your loop to start from 1 instead of 0:
    for i in range(1, len(n)):  # Start at 1 to avoid empty slices
        first = n[:i]
        second = n[i:]
        print(type(first))
        print(type(int(first)))
    
  2. Add a check to skip empty strings before attempting conversion:
    for i in range(len(n)):
        first = n[:i]
        second = n[i:]
        print(type(first))
        if first:  # Only convert if first isn't empty
            print(type(int(first)))
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 15:54:04