1

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
styvane
  • 59,869
  • 19
  • 150
  • 156
2Xchampion
  • 666
  • 2
  • 10
  • 24
  • To find out if you need to prepend a 0 you could check the result of len(str(line)) % 3 – Pedru Apr 12 '16 at 06:31

2 Answers2

2

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
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • Yeah I was thinking why there were two '0' in that padding. But thank you for the prompt response. I finally got it! – 2Xchampion Apr 12 '16 at 06:49
  • One quick question... If I encouter something like this: print(num2txt(65006600660065, k=4)) It would not properly split them. I want them to be thing s like 0065, 0066, 0065. But the code is giving me ['0650', '0660', '0660', '065']...Any ideas? – 2Xchampion Apr 12 '16 at 07:07
  • Sorry for bothering you. I got it. I suggest you might want to edit the padding to switch the place of '00' and '0' which will correctly output when k=4. Thank you! – 2Xchampion Apr 12 '16 at 07:14
  • @HarryLens - My apologies; I've fixed it for the general case (see edit). – TigerhawkT3 Apr 12 '16 at 07:14
  • Thank you! I was trying to something similar. – 2Xchampion Apr 12 '16 at 07:21
1

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']
styvane
  • 59,869
  • 19
  • 150
  • 156