ValueError: invalid literal for int() with base 10: ''

前端 未结 18 1856
甜味超标
甜味超标 2020-11-22 02:06

I am creating a program that reads a file and if the first line of the file is not blank, it reads the next four lines. Calculations are performed on those lines and then t

相关标签:
18条回答
  • 2020-11-22 03:07

    The reason is that you are getting an empty string or a string as an argument into int. Check if it is empty or it contains alpha characters. If it contains characters, then simply ignore that part.

    0 讨论(0)
  • 2020-11-22 03:09

    I found a work around. Python will convert the number to a float. Simply calling float first then converting that to an int will work: output = int(float(input))

    0 讨论(0)
  • 2020-11-22 03:09

    This seems like readings is sometimes an empty string and obviously an error crops up. You can add an extra check to your while loop before the int(readings) command like:

    while readings != 0 | readings != '':
        global count
        readings = int(readings)
    
    0 讨论(0)
  • 2020-11-22 03:10

    The following are totally acceptable in python:

    • passing a string representation of an integer into int
    • passing a string representation of a float into float
    • passing a string representation of an integer into float
    • passing a float into int
    • passing an integer into float

    But you get a ValueError if you pass a string representation of a float into int, or a string representation of anything but an integer (including empty string). If you do want to pass a string representation of a float to an int, as @katyhuff points out above, you can convert to a float first, then to an integer:

    >>> int('5')
    5
    >>> float('5.0')
    5.0
    >>> float('5')
    5.0
    >>> int(5.0)
    5
    >>> float(5)
    5.0
    >>> int('5.0')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: invalid literal for int() with base 10: '5.0'
    >>> int(float('5.0'))
    5
    
    0 讨论(0)
  • 2020-11-22 03:12

    The reason you are getting this error is that you are trying to convert a space character to an integer, which is totally impossible and restricted.And that's why you are getting this error.

    Check your code and correct it, it will work fine

    0 讨论(0)
  • 2020-11-22 03:12

    I was getting similar errors, turns out that the dataset had blank values which python could not convert to integer.

    0 讨论(0)
提交回复
热议问题