Reputation: 667
I have a int 123. I need to convert it to a string "100 + 20 + 3" How can I achieve it using Python?
I am trying to divide the number first (with 100) and then multiple the quotient again with 100. This seems to be pretty inefficient. Is there another way which I can use?
a = 123
quot = 123//100
a1 = quot*100
I am repeating the above process for all the digits.
Upvotes: 1
Views: 1243
Reputation: 261
Here's my approach:
numInput= 123
strNums= str(numInput)
numberList= []
for i in range(0,len(strNums)):
digit= (10**i)*int(strNums[-(i+1)])
numberList.append(str(digit))
final= "+".join(numberList)
print(final)
It's the mathematical approach for what you want. In number system every digit can be denoted as the 10 to the power of the actual place plus number(counting from zero from right to left)
So we took a number and converted into a string. Then in a loop we decided the range of the iteration which is equal to the length of our number. range: 0 to length of number and we give that number of power to the 10, so we would get: 10^0, 10^1, 10^2...
Now we need this value to multiply with the digits right to left. So we used negative index. Then we appended the string value of the digit to an empty list because we need the result in a form as you said.
Hope it will be helpful to you.
Upvotes: -1
Reputation: 9267
Another way of achieving what you intended to do:
def pretty_print(a):
aa = str(a)
base = len(aa) - 1
for v in aa:
yield v + '0' * base
base -= 1
>>> ' + '.join(pretty_print(123))
'100 + 20 + 3'
Upvotes: 1
Reputation: 402854
(Ab)using list comprehension:
>>> num = 123
>>> ' + '.join([x + '0' * (len(str(num)) - i - 1) for i, x in enumerate(str(num))])
'100 + 20 + 3'
How it works:
iteration 0
Digit at index 0: '1' + ('0' * (num_digits - 1 - iter_count) = 2) = '100'
iteration 1
Digit at index 1: '2' + ('0' * 1) = '20'
iteration 2
Digit at index 2: '3' + ('0' * 0) = '3'
Once you've created all the "numbers" and put them in the list, call join
and combine them with the string predicate +
.
Upvotes: 1
Reputation: 7952
Another option would be to do it by the index of the digit:
def int_str(i):
digits = len(str(i))
result = []
for digit in range(digits):
result.append(str(i)[digit] + '0' * (digits - digit - 1))
print ' + '.join(result)
which gives:
>>> int_str(123)
100 + 20 + 3
This works by taking each digit and adding a number of zeroes equal to how many digits are after the current digit. (at index 0
, and a length of 3
, you have 3 - 0 - 1
remaining digits, so the first digit should have 2
zeroes after it.)
When the loop is done, I have a list ["100", "20", "3"]
which I then use join to add the connecting " + "
s.
Upvotes: 1