28
loading...
This website collects cookies to deliver better user experience
%
operator to perform string formatting in Python.%
the operator was gradually replaced with calling the .format()
method on the String object.A brief overview of string formatting in Python. (Made using: https://carbon.now.sh/)
f
or F
and then followed by single, double, or even triple quotes to create your string, e.g., f"Hello, Python!"
.float
decimal places, currency, datetime
objects, and padding with f-stringrepr()
)viewer = "🐊"
owner = "🐼"
editor = "🐓"
print(viewer)
print(owner)
print(editor)
A good way to lose track of which value belongs to which variable.
🐊
🐼
🐓
🐊
🐼 -- Sorry, which variable does this belong to again?
🐓
print(f’{variable_name=}’)
instead.print(f"{viewer=}")
print(f"{owner=}")
print(f"{editor=}")
# Stdout:
# viewer = "🐊"
# owner = "🐼"
# editor = "🐓"
A clearer way to debug print using f-string!
print(f"{viewer= }")
print(f"{owner =}")
print(f"{editor = }")
# Stdout:
# viewer= '🐊'
# owner ='🐼'
# editor = '🐓'
f-string preserves whitespaces.
float
type variables.float
type variable in two decimal places, e.g., making 3.1425123
into 3.14
. Not exactly an uncommon use case, right?round
method to do so. Or perhaps, you’re thinking of using the “older” str.format
way of doing it, such as:# The "old" ways of updating float to 2 decimal places
float_variable = 3.141592653589793
print("%.2f" % float_variable)
print("{:.2f}".format(float_variable))
# Stdout:
# 3.14
# 3.14
Ways of limiting float to two decimal places.
float_variable = 3.141592653589793
print(f"{float_variable:.2f}")
# Stdout:
# 3.14
Using f-string in this scenario is so much easier than str.format()
3142671.76
as $3,142,671.76
.float
value as currency using f-string is extremely handy. We can easily do this by using ,:2f
.money = 3_142_671.76 # 💡 This is the same as 3142671.76
print(f"${money:,.2f}")
# Stdout:
# $3,142,671.76
Format float type variable as a pretty-looking currency. Simple!
float
type variables, we can even use f-string along with datetime
type variable.datetime
object into a more human-friendly manner, such as 05-July-2021
, the most common way of doing so is to use the standard built-in strftime
method of the datetime
object, e.g., datetime_var.strftime(‘%d-%b-%y’)
.datetime
variable. Here’s an example of what I meant:from datetime import datetime
now = datetime.now()
# The usual way
formatted_datetime_now = now.strftime('%d-%B-%Y')
print(formatted_datetime_now)
# F-string way
formatted_datetime_now = f"{now:%d-%B-%Y}"
print(formatted_datetime_now)
# Stdout
# 05-July-2021
Formatting datetime
variable with f-string instead of strftime
.
# Output length of 20, and pad the rest with zeroes
int_variable = 1_234_567
print(f'{int_variable:020}')
# Stdout
# 00000000000001234567
# Output length of 24, and pad the rest with zeroes
int_variable = 30
print(f'{int_variable:024}')
# Stdout
# 000000000000000000000030
Pad your integer typed variable with leading zeroes!
# Output length of 10, and pad the rest with leading whitesplace
int_variable = 20_21
print(f'{int_variable:10d}')
# Stdout
# ' 2021'
# Output length of 5, and pad the rest with leading whitesplace
print(f"{int_variable:5d}")
# Stdout
# ' 2021'
Pad your integer typed variable with leading whitespaces!
!
, followed by your variable in your f-string, it will perform extra conversion on that variable.f’{your_variable!a}’
, just like this:owl = '🦉'
print(f'{owl!a}')
# Stdout
# '\U0001f989'
Shows the ASCII representation of your emoji.
repr()
method in Python.from datetime import datetime
now = datetime.now()
# Using repr()
print(repr(now))
# F-string way
print(f'{now!r}')
# Stdout
# datetime.datetime(2021, 7, 5, 13, 2, 34, 672383)
repr(now) == f'{now!r}'
# True
Using !r
instead of repr()
datetime
object formatting as well as formatting any currency values.