+ 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))

8th Jul 2021, 4:16 PM
partha das
partha das - avatar
4 odpowiedzi
+ 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
8th Jul 2021, 4:26 PM
Angelo
Angelo - avatar
+ 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/
8th Jul 2021, 4:52 PM
Lothar
Lothar - avatar
+ 1
Lothar I see you're a man of culture as well
8th Jul 2021, 4:57 PM
Angelo
Angelo - avatar
+ 1
thanks for the explanation @angelo and @lothar thanks a lot for the additional info ^^
8th Jul 2021, 5:28 PM
partha das
partha das - avatar