+ 1
Could someone please explain what are "0","1" and " "2" doing here {0},{1:0.3f}and{2:0.3f} respectively ? [Solved]
# Find square root of real or complex numbers # Importing the complex math module import cmath num = 1+2j num_sqrt = cmath.sqrt(num) print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag))
4 Answers
+ 5
They are placeholders,
When format sees {0} it replaces it with the "0th" argument (num)
1 refers to num_sqrt.real
2 refers to num_sqrt.imag
+ 6
partha das ,
very good explanation from Angelo !
i just wanted to add that comment:
there is also an other and (recommended) way of doing output like this by using f- strings
the same output can be achieved by using:
print(f'The square root of {num} is {num_sqrt.real:0.3f}+{num_sqrt.imag:0.3f}j')
in contrast to format() function used inside a print statement, we need no additional placeholder + value, the expression or variable name can be placed directly in curly braces. all the other formatting arguments are the same.
here you can also find some more information about output formatting:
https://realpython.com/JUMP_LINK__&&__python__&&__JUMP_LINK-f-strings/
+ 1
Lothar I see you're a man of culture as well
+ 1
thanks for the explanation @angelo and @lothar thanks a lot for the additional info ^^