-1

Example

test = "123456789123"

I tried

test = "1234567"

print(".".join(test))

result

1.2.3.4.5.6.7

but I would like this

result

123.456.789.123
niraj
  • 17,498
  • 4
  • 33
  • 48
Alex Meireles
  • 21
  • 1
  • 3
  • 1
    I find the proposed duplicate strange. It seems as if the op is asking about formatting numbers with thousands separator, not about slicing lists in chunks. – Andrey Tyukin Apr 17 '18 at 01:25
  • 1
    The current link to duplicate redirects to some codon-splitting molecular biologist answer. If you are more interested in formatting numbers with thousands-separator, take a look at [this related question](https://stackoverflow.com/questions/5513615/add-decimal-mark-thousands-separators-to-a-number/49868510#49868510). – Andrey Tyukin Apr 17 '18 at 01:49

5 Answers5

4

Here is a simple regex solution:

import re
print(re.sub(r'(?<!^)(?=(\d{3})+$)', r'.', "12345673456456456"))

It produces the following output:

12.345.673.456.456.456

the regex uses lookahead to check that the number of digits after a given position is divisible by 3.

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
  • 3
    May the downvoter enlighten us all with the only correct solution? If even the accepted answer got two downvotes, there must be a better way, I assume... I actually find solving the problem in a single line by passing two constants and the input string to a standard library method a rather efficient solution, so I'd really appreciate an explanation why this is worth a downvote. – Andrey Tyukin Apr 17 '18 at 01:35
2

If you don't really need a dot, you can simply use:

formated_number = "{:,}".format(value)

And if you really want those dots:

formated_number.replace(',','.')
TwistedSim
  • 1,960
  • 9
  • 23
1

Very naive solution without list comprehension:

test = '123456789123'
result = ''

while test:
    result += test[:3]
    if len(test) > 3:
        result += '.'
    test = test[3:]

print(result)
Daniele Cappuccio
  • 1,952
  • 2
  • 16
  • 31
0

You can loop over the characters as a list and track where you are with a counter:

s = "123456789123"
output = []
count = 0
for c in list(s):
  count += 1
  if count == 4:
    output.append(".")
    count = 0
    continue
  else:
    output.append(c)

result = ''.join(output)
print(result)
JacobIRR
  • 8,545
  • 8
  • 39
  • 68
0

A straightforward implementation:

test = "1234567891234431222334442234ee3432"
testJoined = ""

for i in range(0,len(test),3):
    testJoined += test[i:i+3] + "."

print(testJoined[0:-1])

test1:

"1234567891234431222334442234ee3432"

result1:

123.456.789.123.443.122.233.444.223.4ee.343.2

test2:

"1234567891234431222334442234ee34aa32"

result2:

123.456.789.123.443.122.233.444.223.4ee.34a.a32
Nikki Mino
  • 309
  • 1
  • 2
  • 12