-4

While i was participating in an online python competition i got stuck in a small operation, the thing is that, i need to convert an integer 0000 to a string. but by using str(0000) will give only '0' as the output similarly i need to convert numbers like 0001,0003,0000,00045,0003.

I am expecting str(0000)='0000'
hpaulj
  • 221,503
  • 14
  • 230
  • 353
yzcop
  • 21
  • 4
  • 4
    That doesn't make any sense. `0000` is the number `0`, or zero. There's no way for the interpreter to know that it's supposed to save those extra zeroes. – TigerhawkT3 Feb 11 '17 at 07:10
  • Where did you get that number from? – math2001 Feb 11 '17 at 07:11
  • 4
    I'm also confused, if you're given them as integers in the first place, how do you know how many zeroes there were? – Elizabeth S. Q. Goodman Feb 11 '17 at 07:11
  • Explore the string `format` method. Or you might have to build up the string character by character. `''0'*4` produces '0000'. – hpaulj Feb 11 '17 at 07:12
  • An integer literal starting with a leading 0 (other than 0 itself) is a syntax error in Python3.x anyway - due to the "0" prefix that marked octal numbers Python2 foolishly copied from C. – jsbueno Feb 11 '17 at 07:12
  • @TigerhawkT3 Thanks for the answer. what if i need to get the count of zeros in the integer.? – yzcop Feb 11 '17 at 07:13
  • You cannot assign the number of digits to an integer using the Python int type. Yet you can always try to print int to the formatted string with zero left padding. Check out http://stackoverflow.com/questions/339007/nicest-way-to-pad-zeroes-to-string – Neo X Feb 11 '17 at 07:14
  • 1
    you could use `zfill()`. `str(1).zfill(3)` returns `'001'` in the interpreter. – Steampunkery Feb 11 '17 at 07:15
  • The question is where did you find the integer `0000`? Certainly the compiler won't give you that. – Mohammad Yusuf Feb 11 '17 at 07:17
  • 2
    I don't know the problem specification you read in the contest, but i'm pretty sure you can read them as string in the first place. – Fallen Feb 11 '17 at 07:36
  • The cause of your problem seems to be that you think there is such a thing as integer 0000. There isn't. 0000 is 0. Because of that, str(0000) is '0'. – zvone Feb 11 '17 at 09:51

2 Answers2

0

In the example by Jonathan, 0045 becomes 37 because 0045 is considered as octal by the interpreter. 4*8+5=37. Usually in cases like this, we will not start with leading zeroes. we will start with 45. Hence the answer will be consistent. leading zeroes in string form provide a way for the interpreter to understand octal representation. Hope this helps.

NandR
  • 51
  • 1
  • 1
0

Pad your string.

print('{:0>4}'.format(str(1)))

prints 0001 while

print('{:0>4}'.format(str(123456)))

prints 123456.

You can check https://pyformat.info for more info on .format().

grofte
  • 1,839
  • 1
  • 16
  • 15