So, let's try taking the problem, and writing the rough framework of what we have to do. Notice that whenever I run into a problem that isn't immediately obvious, I push it into its own function, which I can deal with later:
string = str(number)
if len(string) > 5:
string = truncate_string(string)
elif len(string) < 5:
string = pad_string_with_zeros(string)
So, let's try implementing truncate_string
and pad_string_with_zeros
.
A string is basically a list of characters. How would we get the first 5 elements of a list? Through list slicing. Therefore, we can implement truncate_string
like so:
def truncate_string(string):
return string[:5]
How do we pad strings with zeros? Well, if you consult the Python documentation, you could use the ljust
function:
>>> '11'.ljust(5, '0')
'11000'
>>> '12345678'.ljust(5, '0')
'12345'
Therefore, our function could be:
def pad_string_with_zeros(string):
return string.ljust(5, '0')
Alternatively, we could have used a while
loop:
def pad_string_with_zeros(string):
while len(string) < 5:
string += '0'
...although that'll be more inefficient.
If we move all our functions into the main code, then we might get something like this:
string = str(number)
if len(string) > 5:
string = string[:5]
elif len(string) < 5:
string = string.ljust(5, '0')
As it turns out, list slicing will not throw errors, even if you pass in too small or too large strings. For example, '12'[:5]
will result in the string '12'
.
Therefore, we don't need to even check for the size of the string, and can compact it down to the following lines:
string = str(number)
string = string[:5].ljust(5, '0')