2

I have a big number in a variable, what I want is that every 5'th is separated ba a space

Code:

number = 123456789012345678901234567890
print "the number is:", number #Devide every 5'th 

The output I want is:

The number is: 12345 67890 12345 67890 12345 67890
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
joar
  • 312
  • 2
  • 11
  • 2
    Use the solutions from [here](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) and then join the returned list using `str.join`.(Don't forget to convert number to a `string` or `list`) – Ashwini Chaudhary Jan 17 '14 at 22:04
  • This solution is also nice: http://stackoverflow.com/a/21162948/846892 – Ashwini Chaudhary Jan 17 '14 at 22:09

4 Answers4

6
In [1]: number = 123456789012345678901234567890

In [2]: num = str(number)

In [3]: print ' '.join(num[i:i+5] for i in xrange(0,len(num),5))
12345 67890 12345 67890 12345 67890
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
1

This is certainly not elegant, but

rep = str(number)
line = ""
for i, char in enumerate(rep):
    line+=char
    if (i+1)%5 == 0:
        line+=" "
print line
Paul Becotte
  • 9,767
  • 3
  • 34
  • 42
0

The most compact way is to do this with a regular expression. For example:

>>> s ="123456789012345678901234567890"
>>> re.sub('(\d{5})', r'\1 ', s)
12345 67890 12345 67890 12345 67890

if you want to get all groups as a list you can do this:

>>> re.findall('(\d{5})', s)
['12345', '67890', '12345', '67890', '12345', '67890']

which you can then join:

>>> " ".join(re.findall('(\d{5})', s))
12345 67890 12345 67890 12345 67890
Dmitry B.
  • 9,107
  • 3
  • 43
  • 64
0

If you had a general grouper function, this would be trivial:

print ' '.join(grouper(num, 5))

And it's easy to write that function. In fact, there are two different ways to do it.


Slicing—as in inspectorG4dget's answer—only works on sequences, and gives you an incomplete group if there's part of a group left at the end. If that fits your requirements—and for your question, it does—it's definitely simpler, and a little faster.

Here's a general-purpose grouper:

def grouper(sequence, n):
    return (sequence[i:i+n] for i in xrange(0, len(sequence), n))

Iterator grouping is more complicated, but it works on any iterable, even one-shot iterators, and is easy to customize for any of the three reasonable behaviors for trailing values.

You can find a recipe in the itertools docs, but here's a slightly shorter version (which truncates a partial group at the end):

def grouper(iterable, n):
    return zip(*[iter(iterable)]*n)

Or, if you install the more_itertools library, you can just import an implementation from there.

How grouper works explains how this implementation works.

abarnert
  • 354,177
  • 51
  • 601
  • 671