-1
a="1234"
for i in range(0,4):
            for k in range(i,4):
                s=int(a[i:k])
                print s

Output:

Traceback (most recent call last):
  File "C:/Python27/Solutions/test.py", line 4, in <module>
    s=int(a[i:k])
ValueError: invalid literal for int() with base 10: ''

can anybody tell me why I am getting this error ? i just want to print: 1 12 123 1234 2 23 234 and so on...

2 Answers2

2
>>> a= "1234"
>>> a[0:0]   # in slice if start and end is same you will get empty string
''
>>> int(a[0:0])
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
>>> 

i think you want this??

>>> for i in range(3):
...     for k in range(i,4):
...         print int(a[i:k+1])
... 
1
12
123
1234
2
23
234
3
34
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
0

You are receiving this error because the first iteration of your loop (i=0,k=0) takes a[0:0]='' (empty string). Characters and numerical strings can be converted to integers, but an empty string isn't a character or string. It's the absence of characters.

If you were to guard this case your loop would subsequently take substrings of a (example '123', i=0, k=3) and this could be converted to the integer 123. The rest of the cases should output the desired integers just fine.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Freestyle076
  • 1,548
  • 19
  • 36