bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Python/Foundations
Python•Foundations

Python String Formatting

F-String was introduced in Python 3.6, and is now the preferred way of formatting strings.

Before Python 3.6 we had to use the format() method.

F-Strings

F-string allows you to format selected parts of a string.

To specify a string as an f-string, simply put an f in front of the string literal, like this:

Example

txt = f"The price is 49 dollars"

print(txt)

Placeholders and Modifiers

To format values in an f-string, add placeholders {} , a placeholder can contain variables, operations, functions, and modifiers to format the value.

price

A placeholder can also include a modifier to format the value.

A modifier is included by adding a colon : followed by a legal formatting type, like .2f which means fixed point number with 2 decimals:

Example

price = 59

txt = f"The price is {price:.2f} dollars"

print(txt)

You can also format a value directly without keeping it in a variable:

95

Perform Operations in F-Strings

You can perform Python operations inside the placeholders.

Example

txt = f"The price is {20 * 59} dollars"

print(txt)

Expected output

txt = f"The price is {20 * 59} dollars" print(txt)

You can do math operations

You can perform math operations on variables:

Example

price = 59

tax = 0.25

txt = f"The price is {price + (price * tax)} dollars"

print(txt)

You can perform if...else statements inside the placeholders:

Example

price = 49

txt = f"It is very {'Expensive' if price>50 else 'Cheap'}"

print(txt)

Execute Functions in F-Strings

You can execute functions inside the placeholder:

upper()

The function does not have to be a built-in Python method, you can create your own functions and use them:

Example

def myconverter(x):

  return x * 0.3048

txt = f"The plane is flying at a {myconverter(30000)} meter altitude"

print(txt)

More Modifiers

At the beginning of this chapter we explained how to use the .2f modifier to format a number into a fixed point number with 2 decimals.

There are several other modifiers that can be used to format values:

Example

price = 59000

txt = f"The price is {price:,} dollars"

print(txt)

Here is a list of all the formatting types.

Formatting Types
:<Left aligns the result (within the available space)
:>Right aligns the result (within the available space)
:^Center aligns the result (within the available space)
:=Places the sign to the left most position
:+Use a plus sign to indicate if the result is positive or negative
:-Use a minus sign for negative values only
:Use a space to insert an extra space before positive numbers (and a minus sign before negative numbers)
:,Use a comma as a thousand separator
:_Use a underscore as a thousand separator
:bBinary format
:cConverts the value into the corresponding Unicode character
:dDecimal format
:eScientific format, with a lower case e
:EScientific format, with an upper case E
:fFix point number format
:FFix point number format, in uppercase format (show inf and nan as INF and NAN )
:gGeneral format
:GGeneral format (using a upper case E for scientific notations)
:oOctal format
:xHex format, lower case
:XHex format, upper case
:nNumber format
:%Percentage format

String format()

Before Python 3.6 we used the format() method to format strings.

The format() method can still be used, but f-strings are faster and the preferred way to format strings.

The next examples in this page demonstrates how to format strings with the format() method.

The format() method also uses curly brackets as placeholders {} , but the syntax is slightly different:

Example

price = 49
txt = "The price is {} dollars"
print(txt.format(price))

You can add parameters inside the curly brackets to specify how to convert the value:

Example

txt = "The price is {:.2f} dollars"

Check out all formatting types in our String format() Reference .

Multiple Values

If you want to use more values, just add more values to the format() method:

print(txt.format(price, itemno, count))

Example

quantity = 3
itemno = 567
price = 49
myorder = "I want {} pieces of
item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))

Index Numbers

You can use index numbers (a number inside the curly brackets {0} ) to be sure the values are placed in the correct placeholders:

Example

quantity = 3
itemno = 567
price = 49
myorder = "I want {0} pieces of
item number {1} for {2:.2f} dollars."
print(myorder.format(quantity, itemno, price))

Also, if you want to refer to the same value more than once, use the index number:

Example

age = 36
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age,
name))

Named Indexes

You can also use named indexes by entering a name inside the curly brackets {carname} , but then you must use names when you pass the parameter values txt.format(carname = "Ford") :

Example

myorder = "I have a {carname}, it is a {model}."
print(myorder.format(carname
= "Ford", model = "Mustang"))

Previous

Python Try Except

Next

Python None

This chapter

Overview
100

Lessons

265m

Read time

1. Python Tutorial2. Python Introduction3. Python Getting Started4. Python Syntax5. Python Statements6. Python Output / Print7. Python Output Numbers8. Python Comments9. Python Variables10. Python - Variable Names11. Python Variables - Assign Multiple Values12. Python - Output Variables13. Python - Global Variables14. Python Data Types15. Python Numbers16. Python Casting17. Python Strings18. Python - Slicing Strings19. Python - Modify Strings20. Python - String Concatenation21. Python - Format - Strings22. Python - Escape Characters23. Python - String Methods24. Python Booleans25. Python Operators26. Python Arithmetic Operators27. Python Assignment Operators28. Python Comparison Operators29. Python Logical Operators30. Python Identity Operators31. Python Membership Operators32. Python Bitwise Operators33. Python Operator Precedence34. Python Lists35. Python - Access List Items36. Python - Change List Items37. Python - Add List Items38. Python - Remove List Items39. Python - Loop Lists40. Python - List Comprehension41. Python - Sort Lists42. Python - Copy Lists43. Python - Join Lists44. Python - List Methods45. Python Tuples46. Python - Access Tuple Items47. Python - Update Tuples48. Python - Unpack Tuples49. Python - Loop Tuples50. Python - Join Tuples51. Python - Tuple Methods52. Python Sets53. Python - Access Set Items54. Python - Add Set Items55. Python - Remove Set Items56. Python - Loop Sets57. Python - Join Sets58. Python frozenset59. Python - Set Methods60. Python Dictionaries61. Python - Access Dictionary Items62. Python - Change Dictionary Items63. Python - Add Dictionary Items64. Python - Remove Dictionary Items65. Python - Loop Dictionaries66. Python - Copy Dictionaries67. Python - Nested Dictionaries68. Python Dictionary Methods69. Python If Statement70. Python Elif Statement71. Python Else Statement72. Python Shorthand If73. Python Logical Operators74. Python Nested If75. Python Pass Statement76. Python Match77. Python While Loops78. Python For Loops79. Python Functions80. Python Function Arguments81. Python *args and **kwargs82. Python Scope83. Python Decorators84. Python Lambda85. Python Recursion86. Python Generators87. Python range88. Python Arrays89. Python Iterators90. Python Modules91. Python Datetime92. Python Math93. Python JSON94. Python RegEx95. Python PIP96. Python Try Except97. Python String Formatting98. Python None99. Python User Input100. Python Virtual Environment

On this page

F-StringsPlaceholders and ModifiersPerform Operations in F-StringsExecute Functions in F-StringsMore ModifiersString format()Multiple ValuesIndex NumbersNamed Indexes