1

When I try to split a string of numbers with '0', it gives me a wrong output.

for x in str(0123):
    print x
8
3

But if there is no 0, it is correct.

for x in str(1234):
    print x
1
2
3
4

Can anyone help with this?

AGN Gazer
  • 8,025
  • 2
  • 27
  • 45
TYL
  • 1,577
  • 20
  • 33

1 Answers1

3

When you put in the number 0123, it is put in as an integer. Integers have no leading zeros built in, so it reduces itself to 123 before it's converted to the string by the str() function.

So your program is seeing str(123) instead of str(0123).

You can fix this by making the number a string by use of quotes instead of str():

for x in "0123":
    print x

Edit: Based on a comment, I realized my explanation had an error. Although the stuff about the integers having no leading zeros built in, there's actually a behavior in Python 2 that does something different.

Integers written with leading zeroes are octal numbers in python. So when you put 0123, str() isn't seeing 123 like I said, it's actually seeing 1*8^2+2*8+3 = 83, and converts str(83), which is the output you are getting.

Regardless, closing the number in quotes still gets you what you want, just for a different reason than I was thinking.

Davy M
  • 1,697
  • 4
  • 20
  • 27