Thread: Int to Str

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    3
    Rep Power
    0

    Int to Str


    Hi,
    I have an input less than 99
    I need a result that will show two digit output
    eg 05 if input 5, 13 if input 13.
    Because it is only starting course I cannot use if, only use arithmetic operations and greatest integer (//) and remainder (%).
    I am very confused
    THanks in Advance
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,855
    Rep Power
    481
    Omitting the theory lesson about representation of numbers and that Intel processors are designed to be really good at finding remainders leaves us with only the solution. After viewing these answers I'm sure you'll agree that the program would be worse with an "if" statement. "if" could work though.
    Code:
    # 3 solutions
    
    for i in (5,27,):
        print('\n'*2)
    
        print('%d%d'%divmod(i,10), 'divmod')
    
        ones = i % 10   # remainder after dividing by 10
        tens = int(i/10) # works with both modern versions of python.  If you're feeling advanced look up the // operator.
        print('{}{}'.format(tens,ones), 'explicit divmod')
    
        print('{:0>2d}'.format(i), 'string formatting')
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    3
    Rep Power
    0
    Thanks, but found this
    Code:
    print( str(n//10)+str(n%10))

    Comments on this post

    • b49P23TIvg agrees : yup, that works too. I'll bet divmod is faster.
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,855
    Rep Power
    481

    know the builtin methods!


    Another solution:

    '{}'.format(n).zfill(2)
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo