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?
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()
+ 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
+ 4
You could use f-strings:
x = 1234
print(f"x is {x}")
+ 3
Format is old-school!
Use f string which is easy to read and understand
x = 5
y = 3
print(f'{x},{y}')
+ 2
The syntax which helped me was print("{:02d} ". format(hoursCount),":"," {:02d} ". format(minutesCount),":"," {02d} ". format(secondsCount))
+ 1
here you are,Ivan
https://code.sololearn.com/c53yJghejOdn/?ref=app
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
0
Thanks, these are useful!
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?