Skip to content Skip to sidebar Skip to footer

Python - How To Add Space On Each 3 Characters?

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 o

Solution 1:

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

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

Then ' '.join the result.

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

Note that:

>>> [''.join(x) for x inzip(*[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 ...

Solution 2:

Best Function based on @mgilson's answer

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

output example:

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

or for , example:

>>>deflitering_by_three(a):>>>return','.join([a[i:i + 3] for i inrange(0, len(a), 3)])>>>#  replace (↑) with you character like ",">>>print(litering_by_three(x))
'500,000'
>>>

Solution 3:

a one-line solution will be

" ".join(splitAt(x,3))

however, Python is missing a splitAt() function, so define yourself one

defsplitAt(w,n):
    for i inrange(0,len(w),n):
        yield w[i:i+n]

Solution 4:

How about reversing the string to jump by 3 starting from the units, then reversing again. The goal is to obtain "12 345".

n="12345"" ".join([n[::-1][i:i+3] for i in range(0, len(n), 3)])[::-1]

Solution 5:

Join with '-' the concatenated of the first, second and third characters of each 3 characters:

' '.join(a+b+c for a,b,c in zip(x[::3], x[1::3], x[2::3]))

Be sure string length is dividable by 3

Post a Comment for "Python - How To Add Space On Each 3 Characters?"