Python Print Formatting Guide
In Python, print formatting is used to insert the value of variables into a string so that it can be displayed when outputting. It has various methods available for this purpose.
- Using placeholders: Using placeholders in a string (such as %s, %d, %f), and then using the % operator to insert the value of variables into the string. For example:
name = "Alice"
age = 25
print("My name is %s and my age is %d" % (name, age))
- Utilize the format function by using curly braces as placeholders in a string, passing the variables to be inserted into the function. For example:
name = "Alice"
age = 25
print("My name is {} and my age is {}".format(name, age))
- Use f-string: Add the letter “f” before a string, then use curly braces as placeholders within the string and write the variable to be inserted within the curly braces. For example:
name = "Alice"
age = 25
print(f"My name is {name} and my age is {age}")
All of these methods can be used to format printed output, choose the appropriate method based on specific needs.