+ 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?
8 Réponses
+ 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
+ 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]}")
+ 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/
+ 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/
+ 1
Try to change the numbers in curly braces, then you will realize.
+ 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.
+ 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?
0
Lothar, f- string looks far more clear to me. Is there any benefit over using one over another (format() or f-string)?