-5

Given a number like 12345678910 I want to output number id 123.456.789-10.

I tried this:

print('number id {0:1.3}.{0:1.3}.{0:1.3}-{0:1.3}'.format("12345678910"))

but the result is number id 123.123.123-123. How to do this correctly?

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
Alex Meireles
  • 21
  • 1
  • 3

1 Answers1

0

This is one way to achieve what you are looking to do:

number = "12345678910"
print(
    'number id {0}.{1}.{2}-{3}'.format(
        *[number[i:i+3] for i in range(0,len(number), 3)]
    )
)
#number id 123.456.789-10.

There are a few problems with your code. First the first number in the "{0...}" refers to the positional argument in the format() function. In your case, you were using all 0 which refers to the first argument only. This is why the same substring was being repeated over and over. (Notice how I changed it to {0}.{1}...{3}.)

I am passing *[number[i:i+3] for i in range(0,len(number), 3)] to the format function, which just breaks your string into chunks of 3.

print([number[i:i+3] for i in range(0,len(number), 3)])
#['123', '456', '789', '10']

The * operator does argument unpacking, which passes the elements of the list in order to format().


Update:

As @user2357112 mentioned in the comments, you don't actually need anything inside the braces in this case. Just use {} to represent placeholders.

print(
    'number id {}.{}.{}-{}'.format(
        *[number[i:i+3] for i in range(0,len(number), 3)]
    )
)
pault
  • 41,343
  • 15
  • 107
  • 149