Python String Formatting
- Previous Page Python Command Input
- Next Page Python File Open
To ensure that the string is displayed as expected, we can use format()
method formats the result.
string format()
format()
methods allow you to format selected parts of the string.
Sometimes part of the text is beyond your control, perhaps they come from a database or user input?
To control such values, add placeholders (curly braces {}
),then run the values through the format() method:
Example
Add a placeholder for the price to be displayed:
price = 52 txt = "The price is {} dollars" print(txt.format(price))
You can add parameters inside the curly braces to specify how to convert the values:
Example
Format the price as a number with two decimal places:
txt = "The price is {:.2f} dollars"
See all format types in the string format() reference manual.
Multiple values
If you need more values, just add more values to the format() method:
print(txt.format(price, itemno, count))
And add more placeholders:
Example
quantity = 3 itemno = 567 price = 52 myorder = "I want {} pieces of item number {} for {:.2f} dollars." print(myorder.format(quantity, itemno, price))
Index Number
You can use the index number (curly braces {0}
to ensure that the value is placed in the correct placeholder:
Example
quantity = 3 itemno = 567 price = 52 myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars." print(myorder.format(quantity, itemno, price))
Additionally, if you need to refer to the same value multiple times, please use the index number:
Example
age = 63 name = "Bill" txt = "His name is {1}. {1} is {0} years old." print(txt.format(age, name))
Named Indexes
You can also use the number within the curly braces {carname}
Enter a name to use named indexes, but when passing parameter values txt.format(carname = "Ford") must use the name:
Example
myorder = "I have a {carname}, it is a {model}." print(myorder.format(carname = "Porsche", model = "911"))
- Previous Page Python Command Input
- Next Page Python File Open