ValueError: invalid literal for int() with base 10: '' - string to int conversion

StackOverflow https://stackoverflow.com/questions/22720080

  •  23-06-2023
  •  | 
  •  

Question

I am trying to convert a numeric string to int, but I keep getting the following:

Traceback (most recent call last):
  File "C:/Python34/Euler36.py", line 16, in <module>
    rev = int(rev)
ValueError: invalid literal for int() with base 10: ''

I've looked at several threads for similar errors, but none that seem to be having trouble with an empty string value: ''

I'm just using ''.join() to concatenate the list into a string, and thought I could use int() to convert the string to int. Seemingly not. Here's the code:

num = 0
temp = 0
add_digit = 0
rev = []
length = 100 #All numbers less than this

while num < length:
    temp = num
    rev = []
    while temp > 0:
        add_digit = temp % 10
        temp /= 10
        temp = int(temp)
        rev.append(str(add_digit))
    rev = ''.join(rev)
    rev = int(rev)
    print(rev)
    num += 1

print("Done.")
Était-ce utile?

La solution

You start with num = 0. You then set temp = num, so temp is zero. Thus your while temp > 0 loop never runs, and so nothing is ever added to rev. So when you try to use join, it just joins an empty list and produces an empty string.

How to fix this is unclear, since you don't say what you want the code to do.

Autres conseils

num in the first iteration is 0, and your while is not entered. Thus rev is an empty string.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top