Skip to content

Instantly share code, notes, and snippets.

@ngshiheng
Last active February 7, 2022 05:48
Show Gist options
  • Save ngshiheng/51be8062ee7df625bc7c99b2397356fd to your computer and use it in GitHub Desktop.
Save ngshiheng/51be8062ee7df625bc7c99b2397356fd to your computer and use it in GitHub Desktop.
3 Useful Python F-string Tricks You Probably Don’t Know https://jerrynsh.com/3-useful-python-f-string-tricks-you-probably-dont-know/
viewer = "🐊"
owner = "🐼"
editor = "🐓"
print(viewer)
print(owner)
print(editor)
print(f"{viewer=}")
print(f"{owner=}")
print(f"{editor=}")
# Stdout:
# viewer = "🐊"
# owner = "🐼"
# editor = "🐓"
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
print(f"{viewer= }")
print(f"{owner =}")
print(f"{editor = }")
# Stdout:
# viewer= '🐊'
# owner ='🐼'
# editor = '🐓'
# 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
float_variable = 3.141592653589793
print(f"{float_variable:.2f}")
# Stdout:
# 3.14
money = 3_142_671.76 # 💡 This is the same as 3142671.76
print(f"${money:,.2f}")
# Stdout:
# $3,142,671.76
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
# 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
# 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'
owl = '🦉'
print(f'{owl!a}')
# Stdout
# '\U0001f989'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment