Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to add space on each 3 characters?

Tags:

python

I need to add a space on each 3 characters of a python string but don't have many clues on how to do it.

The string:

345674655

The output that I need:

345 674 655   

Any clues on how to achieve this?

Best Regards,

like image 214
André Avatar asked Mar 06 '13 17:03

André


People also ask

How do you add a space to a string in Python?

Use the str. ljust() method to add spaces to the end of a string, e.g. result = my_str. ljust(6, ' ') . The ljust method takes the total width of the string and a fill character and pads the end of the string to the specified width with the provided fill character.


2 Answers

You just need a way to iterate over your string in chunks of 3.

>>> a = '345674655'
>>> [a[i:i+3] for i in range(0, len(a), 3)]
['345', '674', '655']

Then ' '.join the result.

>>> ' '.join([a[i:i+3] for i in range(0, len(a), 3)])
'345 674 655'

Note that:

>>> [''.join(x) for x in zip(*[iter(a)]*3)]
['345', '674', '655']

also works for partitioning the string. This will work for arbitrary iterables (not just strings), but truncates the string where the length isn't divisible by 3. To recover the behavior of the original, you can use itertools.izip_longest (itertools.zip_longest in py3k):

>>> import itertools
>>> [''.join(x) for x in itertools.izip_longest(*[iter(a)]*3, fillvalue=' ')]
['345', '674', '655']

Of course, you pay a little in terms of easy reading for the improved generalization in these latter answers ...

like image 87
mgilson Avatar answered Oct 21 '22 00:10

mgilson


Best Function based on @mgilson's answer

def litering_by_three(a):
    return ' '.join([a[i:i + 3] for i in range(0, len(a), 3)])
#  replace (↑) with you character like ","

output example:

>>> x="500000"
>>> print(litering_by_three(x))
'500 000'
>>> 

or for , example:

>>> def litering_by_three(a):
>>>         return ','.join([a[i:i + 3] for i in range(0, len(a), 3)])
>>>     #  replace (↑) with you character like ","
>>> print(litering_by_three(x))
'500,000'
>>> 
like image 42
Ebrahim Karimi Avatar answered Oct 20 '22 23:10

Ebrahim Karimi