Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split string by N symbols in Python from the end of the string

I need to split the string from the end.
For example, I have

word = '3640000'

And it is easy to split it from the begin of the string using list generator and .join method:

word = ' '.join([word[i:i + 3] for i in range(0, len(word), 3)])

In this case I get result: ‘364 000 0’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

but I need get: "3 640 000"

How can I solve this task?

I tried something like this, but it is not working for me if a word is not divisible by 3 without remainder

list1 = []
for i in range(len(word) - 1, -1, -3):
    print(word[i-2:i+1])
    list1.append(word[i-2:i+1])
list1.reverse()

>Solution :

It’s a bit hacky, we can use Python’s string formatting to do the grouping, then replace the separator (Python only allows "," and "_" as grouping characters).

>>> w = '3640000'
>>> f'{int(w):,d}'.replace(',', ' ')
'3 640 000'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading