Meliksah - 4 months ago 20

Python Question

I started to learn Python but I'm stuck on string formatting. I was just playing code but I couldn't understand why below behavior occurs.

Can anyone explain it?

Code:

`nums = [4, 5, 6]`

msg = "Numbers: {0} {2} {1} {2}". format(nums[1], nums[2], nums[1])

print(msg)

Output:

`Numbers: 5 5 6 5`

Answer

You are using `format`

function.

It would take `{number of parameter in format function}`

that you define in brackets.

Let's do some preprocessing for msg line:

```
nums = [4, 5, 6]
msg = "Numbers: {0} {2} {1} {2}". format(nums[1], nums[2], nums[1])
```

is equal to

```
msg = "Numbers: {0} {2} {1} {2}". format(5, 6, 5)
```

because you are taking elements from `nums`

list by indexes (0 based index)

And finally `{number}`

in format would take it from arguments:

```
msg = "Numbers: 5 5 6 5". format(5, 6, 5)
```

So `{0}`

and `{2}`

are equals to 5 and
`{1}`

is equal to 6