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)]
)
)
0
solved Use a formatted string to separate groups of digits