String Formating

f-strings (Python 3.6+):

name = "Charlie"
weight = 68.5

formatted_string = f"My name is {name} and I weigh {weight:.2f} kg."
print(formatted_string)

.2f inside {weight:.2f} specifies formatting for the floating-point number.

format() method

name = "Alice"
age = 30
height = 165.75

formatted_string = "My name is {} and I am {} years old. My height is {:.2f} cm.".format(name, age, height)
print(formatted_string)

Last updated