+ 1

Python .format() Question

Hello, beginner coder here, nums = [4, 5, 6] msg = "Numbers: {0} {1} {2}". format(nums[0], nums[1], nums[2]) print(msg) Take this code for example. What do the numbers in the curly braces do exactly? Also, how do the curly braces relate to the square brackets?

16th Jul 2022, 7:34 AM
Zane Al-Hamwy
Zane Al-Hamwy - avatar
8 Respuestas
+ 4
here { } is called placeholder that should be replaced by values or parameters passed to function based on the index on { } {0} replaced by nums[0] {1} replaced by nums[1] {2} replaced by nums[2] so output should be Numbers : 4 5 6
16th Jul 2022, 7:47 AM
Aly Alsayed
Aly Alsayed - avatar
+ 4
Zane Al-Hamwy , just to mention that the output can also be done with string interpolation/ f-string. we can place the output variable direct inside curly braces: print(f"Numbers: {nums[0]} {nums[1]} {nums[2]}")
16th Jul 2022, 11:10 AM
Lothar
Lothar - avatar
+ 3
Zane Al-Hamwy , this link leads to an article that compares the 3 possible ways to format output: https://realpython.com/JUMP_LINK__&&__python__&&__JUMP_LINK-string-formatting/
17th Jul 2022, 4:27 PM
Lothar
Lothar - avatar
+ 2
Syntax of format() function: { }.format(value) Parameters: value : Can be an integer, floating point numeric constant, string, characters or even variables. Returntype: Returns a formatted string with the value passed as parameter in the placeholder position. ref: https://www.geeksforgeeks.org/JUMP_LINK__&&__python__&&__JUMP_LINK-string-format-method/
16th Jul 2022, 7:46 AM
Aly Alsayed
Aly Alsayed - avatar
+ 1
Try to change the numbers in curly braces, then you will realize.
16th Jul 2022, 7:45 AM
GnoL
+ 1
Don't understand why someone downvoted GnoL answer. Playing with the indeces in curly brackets is actually helpful in understanding this function. When the quantities of curly brackets and arguments to format are equal, it's also interesting to see the effect of removing the numbers inside the curly brackets.
16th Jul 2022, 4:55 PM
Emerson Prado
Emerson Prado - avatar
+ 1
Aly Alsayed, I think your answer is making more sense to me. Knowing now that {} is simply a placeholder, does this mean it has no affect on the output?
16th Jul 2022, 5:20 PM
Zane Al-Hamwy
Zane Al-Hamwy - avatar
0
Lothar, f- string looks far more clear to me. Is there any benefit over using one over another (format() or f-string)?
16th Jul 2022, 5:22 PM
Zane Al-Hamwy
Zane Al-Hamwy - avatar