0

So, I have double-digit numbers below 100. Below 10 python doesn't handle them out-of-the-box. I have seen many different solutions, but I'm just fine with converting them to strings and then check whether the it starts with 0.

The below code is just a sample test of checking the above condition, but fails:

num = 01
if str(num).startswith('0'):
    print 'yepp'
else:
    print 'nope'

I keep getting "nope" for this very example. Why?

fishmong3r
  • 1,414
  • 4
  • 24
  • 51
  • Please see http://stackoverflow.com/q/11620151/5827958 – zondo Apr 05 '17 at 16:43
  • 2
    `01` is not a double-digit number. It's just `1`. (Actually, it's an octal literal, because of the leading `0`. Python won't even accept something like `08`, because `8` isn't an octal digit. On Python 3, octal literals need to start with `0o`, and Python 3 won't accept `01` at all.) – user2357112 Apr 05 '17 at 16:43
  • @user2357112 So if `08` is the input, how to convert it to 8 (int). Because I can't do any math stuff with a variable like `num = 08`. I get error for `print num*2`. – fishmong3r Apr 05 '17 at 16:45
  • Could you state your number as a list of the digits then ints will work num = [0,1] if str(num[0])==0: print 'yepp' else: print 'nope' – CodeCupboard Apr 05 '17 at 16:48
  • @fishmong3r: If you're reading numbers from user input, use `int(raw_input())` to read the input, interpret it as the base 10 representation of an integer, and produce the corresponding integer. This integer will not track leading zeros, because leading zeros are not a numeric property; if you want to print it with leading zeros, you can use Python's output formatting tools. – user2357112 Apr 05 '17 at 16:49
  • @user2357112 -- I didn't know that the "010"-meaning-8 had been dropped in Python3, but I heartily approve. The syntax probably caused me 1 bug for every 4 times I got any value from it, and that is a terrible ratio. – Michael Lorton Apr 05 '17 at 16:50
  • OP,you can get what I think you want this way: [`"%02d" % num`](https://pyformat.info/). – Michael Lorton Apr 05 '17 at 16:52

2 Answers2

1

num is not a string. It is an integer. The integer 1 does not start with '0' when converted to a string

Devin
  • 1,262
  • 15
  • 20
0

The integer value 01 don't exist, it's equal to 1 in Python 2.x and will produce a SyntaxError in Python 3.x.

Code1:

>>> num = '01'
>>> if str(num).startswith('0'):
>>>     print('yepp')
>>> else:
>>>     print('nope')
yepp

Code2:

>>> num = 01
>>> if str(num).startswith('0'):
>>>     print('yepp')
>>> else:
>>>     print('nope')
File "<ipython-input-4-dafa449070e3>", line 1
  num = 01
         ^
SyntaxError: invalid token

Code3:

>>> num = 1
>>> if str(num).startswith('0'):
>>>     print('yepp')
>>> else:
>>>     print('nope')
nope
dot.Py
  • 5,007
  • 5
  • 31
  • 52