Python Tutorials

Overview

There are two ways to format strings in Python: Using F-strings (the preferred way since v3.6) and the format() method (older and less efficient).

Using the F-String Way

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

txt = f"Hello World"
print(txt)

Output:

Hello World

F-Strings and Placeholders

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

name = "Johnny"
txt = f"My son's name is {name}."

print(txt)

Output:

My son's name is Johnny.

F-Strings, Placeholders and Modifiers

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.

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

print(txt)

Output:

The price is $99.00 dollars.

This can also be done without using a variable. Just place the value within {}.

txt = f"The price is ${99:.2f} dollars."
print(txt)

Output:

The price is 99.00 dollars.

Performing Operations in F Strings

Do math operations:

txt = f"The price is ${10 * 29} dollars."
print(txt)

Output:

The price is $290 dollars.

Using if… else statements:

price = 99
txt = f"${price:.2f} is somewhat {'expensive' if price > 100 else 'affordable'}."

print(txt)

Output:

$99.00 is somewhat affordable.

Execute Built-in Functions in F-Strings

Use the string method upper() to convert a value into upper case letters.

car = "maserati"
txt = f"I enjoy driving my {car.upper()}!"

print(txt)

Output:

I enjoy driving my MASERATI!

Execute Custom Functions in F-Strings

Custom functions can be created and used with f strings.

def myFunction(x):
    return x * 3.14

txt = f"Pie times 4 equals {myFunction(4)}."
print(txt)

Output:

Pie times 4 equals 12.56.

F String 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

Using the format() Method

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

name = "Johnny"
txt = "My son's name is {}."

print(txt.format(name))

Output:

My son's name is Johnny.

The format() Method with Parameters

Parameters can be used inside curly brackets to specify how to convert a value.

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

print(txt.format(price))

Output:

The price is $99.00 dollars.

Using multiple parameters:

quantity = 16
item = 41101
price = 99
order = "We need {} pieces of item {} which cost ${:.2f} each."

print(order.format(quantity, item, price))

Output:

We need 16 pieces of item 41101 which cost $99.00 each.

Using Index Numbers in the Parameter Fields

Index numbers (a number inside the curly brackets) can be used to ensure the values are placed in the correct placeholders. This is similar to creating/using an array.

quantity = 16
item = 41101
price = 99
order = "We need {0} pieces of item {1} which cost ${2:.2f} each."

print(order.format(quantity, item, price))

Output:

We need 16 pieces of item 41101 which cost $99.00 each.

Note

Arrays count starting from zero NOT one. So item 1 is position [0], item 2 is position [1], and item 3 is position [2] … and so on.

Index numbers can also be used when referring to the same value more than once.

age = 12
name = "Johnny"
txt = "My son's name is {1}. {1} is {0} years old."

print(txt.format(age, name))

Output:

My son's name is Johnny. Johnny is 12 years old.

Using Named Indexes in the Parameter Fields

Named indexes can be used by entering a name inside the curly brackets {carname}. Then when passing a parameter, the value is also passed in the format (carname = “Maserati”).

mycar = "I drive a {carname} {carmodel}."
print(mycar.format(carname = "Maserati", carmodel = "Quattroporte"))

Output:

I drive a Maserati Quattroporte.

Python Notes:

  • The most recent major version of Python is Python 3; however, Python 2 is still in use and quite popular, although not being updated with anything other than security updates
  • Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses
  • Python relies on indentation, using whitespace to define scope, such as the scope of loops, functions, and classes; other programming languages often use curly-brackets for this purpose
  • Python string methods return new values, and DO NOT change the original string
  • Python tuples are unchangeable after created (their items CANNOT be changed or re-ordered at a later point)
  • Python sets are unordered (may appear in random orders when called), unchangeable (the value of individual items cannot be changed after creation), unindexed (items cannot be referred to by index or key), and duplicates are NOT ALLOWED
  • As of v3.7, Python dictionaries are ordered and duplicates ARE ALLOWED; in v3.6 and earlier, dictionaries were unordered (did not have a defined order and could not be referred to using an index)
  • Python does not have built-in support for arrays, but Python lists can be used as pseudo “arrays”; therefore, all Python list methods will work with these pseudo “arrays”

We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.