0

Python Formatting

Why does the Following code work: print(("{x},{y}".format(x = int(input()),y = int(input())))) but not the one below: x = int(input()) y = int(input()) print(("{x},{y}".format(x,y))) I understand that one can do this: x = int(input()) y = int(input()) print(("{0},{1}".format(x,y))) But is there another way?

21st Jun 2021, 3:53 PM
Edward Finkelstein
Edward Finkelstein - avatar
10 Answers
+ 5
You could do x = int(input()) y = int(input()) print(("{x},{y}".format(x=x,y=y))) The var name {x} refers to the local name in format()
21st Jun 2021, 4:46 PM
Lisa
Lisa - avatar
+ 5
here some versions to create the discussed output: (1) the mentioned version slightly reworked. it creates an extra space, since a comma is used to separate the arguments (2) same as (1), but using concatenation with '+' (3) using f- string that makes it much shorter and has a better readability hoursCount = 8 minutesCount = 8 secondsCount = 8 print("{:02d}".format(hoursCount),":","{:02d}".format(minutesCount),":","{:02d}".format(secondsCount)) # (1) 08 : 08 : 08 print("{:02d}".format(hoursCount)+":"+"{:02d}".format(minutesCount)+":"+"{:02d}".format(secondsCount)) # (2) 08:08:08 print(f"{hoursCount:02d}:{minutesCount:02d}:{secondsCount:02d}") # (3) 08:08:08
15th Sep 2021, 12:38 PM
Lothar
Lothar - avatar
+ 4
You could use f-strings: x = 1234 print(f"x is {x}")
21st Jun 2021, 4:37 PM
Lisa
Lisa - avatar
+ 3
Format is old-school! Use f string which is easy to read and understand x = 5 y = 3 print(f'{x},{y}')
21st Jun 2021, 4:51 PM
Shadoff
Shadoff - avatar
+ 2
The syntax which helped me was print("{:02d} ". format(hoursCount),":"," {:02d} ". format(minutesCount),":"," {02d} ". format(secondsCount))
15th Sep 2021, 11:48 AM
Ivan Bessarab
Ivan Bessarab - avatar
15th Sep 2021, 10:09 AM
Shadoff
Shadoff - avatar
0
Don't know, i get a KeyError. Must have something to do with the classes and data types in Python. Specifically the dictionary with that KeyError. just use f strings
21st Jun 2021, 4:42 PM
Slick
Slick - avatar
0
Thanks, these are useful!
21st Jun 2021, 5:11 PM
Edward Finkelstein
Edward Finkelstein - avatar
0
How do I format my output using f string if I want to display hh:mm:ss with two digits regardless whether the value is a one digit number, likesay 8:8:8 should be 08:08:08?
14th Sep 2021, 11:59 PM
Ivan Bessarab
Ivan Bessarab - avatar