{"record":{"id":"e2796205b4123a23","repo":"python/cpython","slug":"invalid-literal-for-int-with-base-10","errorCode":null,"errorMessage":"invalid literal for int() with base 10","messagePattern":"invalid literal for int\\(\\) with base 10","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"Lib/_pylong.py","lineNumber":407,"sourceCode":"def int_from_string(s):\n    \"\"\"Asymptotically fast version of PyLong_FromString(), conversion\n    of a string of decimal digits into an 'int'.\"\"\"\n    # PyLong_FromString() has already removed leading +/-, checked for invalid\n    # use of underscore characters, checked that string consists of only digits\n    # and underscores, and stripped leading whitespace.  The input can still\n    # contain underscores and have trailing whitespace.\n    s = s.rstrip().replace('_', '')\n    func = _str_to_int_inner\n    if len(s) >= 2_000_000 and _decimal is not None:\n        func = _dec_str_to_int_inner\n    return func(s)\n\ndef str_to_int(s):\n    \"\"\"Asymptotically fast version of decimal string to 'int' conversion.\"\"\"\n    # FIXME: this doesn't support the full syntax that int() supports.\n    m = re.match(r'\\s*([+-]?)([0-9_]+)\\s*', s)\n    if not m:\n        raise ValueError('invalid literal for int() with base 10')\n    v = int_from_string(m.group(2))\n    if m.group(1) == '-':\n        v = -v\n    return v\n\n\n# Fast integer division, based on code from Mark Dickinson, fast_div.py\n# GH-47701. Additional refinements and optimizations by Bjorn Martinsson.  The\n# algorithm is due to Burnikel and Ziegler, in their paper \"Fast Recursive\n# Division\".\n\n_DIV_LIMIT = 4000\n\n\ndef _div2n1n(a, b, n):\n    \"\"\"Divide a 2n-bit nonnegative integer a by an n-bit positive integer\n    b, using a recursive divide-and-conquer algorithm.\n","sourceCodeStart":389,"sourceCodeEnd":425,"githubUrl":"https://github.com/python/cpython/blob/bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6/Lib/_pylong.py#L389-L425","documentation":"Raised by str_to_int in _pylong, the asymptotically fast decimal-string-to-int helper, when the regex \\\\s*([+-]?)([0-9_]+)\\\\s* does not match: the string (after the caller's rstrip/underscore handling upstream in int()) contains no digits at all or characters outside [0-9_] in the numeric part. It is the internal equivalent of the standard 'invalid literal for int() with base 10' error.","triggerScenarios":"Internal fast-path call str_to_int(''), str_to_int('abc'), str_to_int('12.5') or '1e5' (decimal point / exponent not allowed), or strings with embedded whitespace like '1 2'. User-visible as the familiar ValueError from int('not a number').","commonSituations":"Parsing user input, CSV/JSON-ish data, or file contents with int() without stripping or format checks: empty strings from blank lines, floats-as-strings ('3.14'), hex with prefix ('0x1f' without base 0 or 16), thousands separators ('1,000'), or locale-formatted numbers.","solutions":["Strip and check the string before int(): s = s.strip(); if not s or not s.lstrip('+-').replace('_','').isdigit(): handle the error","If the value may be a float string, route through float() or decimal.Decimal instead","For hex/octal/binary or prefixed literals, call int(s, 0) or int(s, 16) etc.","Remove separators before parsing: s = s.replace(',', '')"],"exampleFix":"# before\nvalue = int(line)          # line is '\\n' or '3.14' -> ValueError\n\n# after\nline = line.strip()\nif not line:\n    return None\ntry:\n    value = int(line)\nexcept ValueError:\n    value = int(float(line))","handlingStrategy":"validation","validationCode":"def parse_int(s):\n    s = s.strip().replace('_', '')\n    if not s or not s.lstrip('+-').isdigit():\n        raise ValueError(f'not an integer: {s!r}')\n    return int(s)","typeGuard":"def is_int_string(s):\n    s = s.strip().lstrip('+-')\n    return s.isdigit()","tryCatchPattern":"try:\n    value = int(raw)\nexcept ValueError as e:\n    if 'invalid literal' in str(e):\n        raw = raw.strip().replace(',', '')\n        value = int(float(raw)) if raw.lstrip('+-').replace('.','',1).isdigit() else None\n    else:\n        raise","preventionTips":["Strip whitespace and reject empty lines before int()","Route float-like strings ('3.14','1e5') through float() or Decimal","Use int(s, 0) for prefixed literals ('0x1f') and int(s, 16) for bare hex"],"tags":["python","int","parsing","valueerror","input-validation"],"backgroundTag":null,"analyzedSha":"bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6","analyzedAt":"2026-08-14T22:01:13.976Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}