String formatting is a technique in Python for creating formatted output that includes variable data. There are several ways to format strings in Python, including the older %-style formatting and the newer .format() method. Here are examples of each:
%-style formatting
name = "Alice"age = 25occupation = "programmer"output = "My name is %s, I am %d years old, and I work as a %s." % (name, age, occupation)print(output) # Output: "My name is Alice, I am 25 years old, and I work as a programmer." |
In this example, %s is used as a placeholder for the name and occupation variables, and %d is used as a placeholder for the age variable. The values are passed as a tuple to the % operator, and the resulting string is stored in the output variable.
.format() method
name = "Bob"age = 30occupation = "teacher"output = "My name is {}, I am {} years old, and I work as a {}.".format(name, age, occupation)print(output) # Output: "My name is Bob, I am 30 years old, and I work as a teacher." |
In this example, {} is used as a placeholder for the name, age, and occupation variables. The values are passed as arguments to the format() method, and the resulting string is stored in the output variable.
The .format() method provides more flexibility than %-style formatting, allowing you to specify the order of the variables, reuse variables, and more. Here is an example:
name = "Charlie"age = 35occupation = "engineer"output = "My name is {0}, I am {1} years old, and I work as a {2}. My name is {0}.".format(name, age, occupation)print(output) # Output: "My name is Charlie, I am 35 years old, and I work as a engineer. My name is Charlie." |
In this example, the first placeholder {0} is used twice to insert the value of the name variable in two places. The resulting string includes the same value twice, but formatted differently.
String formatting is a powerful technique for creating formatted output in Python. It allows you to insert variable data into a string in a flexible and customizable way, making your output more readable and informative.