Reputation: 656
I am attempting to split a string of integers by every n character and then convert them to unicode. Unfortunately, I came across a problem... Since the leading 0s has been dropped from the string, it makes me confused about how to handle them. Here is an example:
print(num2txt(97097114103104))
Here the leading 97 is a valid number in the ASCII table and I can simple add a "0" before the string so that this whole string will be correctly split into something like this:
['097', '097', '114', '103', '104']
However, what if the first three digits are actually valid in the ASCII table? Like this:
100097114103
In this case I want it to be split into
['100', '097', '114']
But how do I make sure this does not need a "0" anymore if something happens in my function?
My current code is below:
def num2txt(num, k=3):
line = str(num)
line = "0" + line
line = [line[i:i+k] for i in range(0, len(line), k)]
return line
Upvotes: 1
Views: 421
Reputation: 61225
I would do this using math.ceil
to round up the length of my string to the multiple of 3
then format
my string. From there to split my string what other better way than using a generator function?
import math
def num2txt(num, k):
num_str = "{:0>{width}}".format(num, width=math.ceil(len(str(num))/k)*k)
for n in range(0, len(num_str), k):
yield num_str[n:n+k]
Demo:
>>> list(num2txt(97097114103104, 3))
['097', '097', '114', '103', '104']
Upvotes: 1
Reputation: 49318
Just add leading zeros when necessary.
def num2txt(num, k=3):
line = str(num)
padding = len(line)%k
if padding:
line = '0'*(k-padding) + line
line = [line[i:i+k] for i in range(0, len(line), k)]
return line
Upvotes: 2