The length of the string needs to be 5 characters. When the string is "1" it needs to be returned as "00001", when the string is "10" it needs to be returned as "00010" and so on. I'm wondering how to do this using loops?
Asked
Active
Viewed 137 times
-1
-
Have you thought using some of the `str` method. The docs have some really good examples and they provide lots of insight. – Zizouz212 Apr 14 '15 at 02:14
-
1Such as [`format`](https://docs.python.org/3/library/functions.html#format) and its [spec](https://docs.python.org/3/library/string.html#formatspec). – TigerhawkT3 Apr 14 '15 at 02:15
-
1`'{:0>5}'.format(string)` – Avinash Raj Apr 14 '15 at 02:15
2 Answers
1
If you want to use for-loops, you can solve the problem like so:
def addPadding(str):
output = ''
# Prepend output with 0s
for i in range(5 - len(str)):
output += '0'
output += str
return output
print(addPadding('10'))
>> 00010
print(addPadding('1'))
>> 00001

Dehli
- 5,950
- 5
- 29
- 44
0
If you can't use string formatting or arrays or anything besides integer operators, you should be able to figure it out using division and a loop.
Is 10 divisible by 10000? Is 10 divisible by 1000? Is 10 divisible by 100? etc.
Try typing 10/10000 in your python interpreter. What's the result? :)

Anthony
- 3,492
- 1
- 14
- 9