Python — f-strings Useful Tricks

Few tricks about using f-strings in Python

Tony
Geek Culture

--

Python f-strings can do much more than just printing out the strings. Let’s explore all the cool things that f-strings can do.

Re-use Variable Name Again

str_value = "hello,python coders"
print(f"{ str_value = }")
# str_value = 'hello,python coders'

Change Output Directly

num_value = 125
print(f"{num_value % 2 = }")
# num_value % 2 = 1

Date formatting

import datetime

today = datetime.date.today()
print(f"{today: %Y%m%d}")
#20211224
print(f"{today =: %Y%m%d}")
#today = 20211224

2/8/16 Hexadecimal Conversion

>>> a = 42
>>> f"{a:b}"# Binary
'101010'
>>> f"{a:o}"# Octal
'52'
>>> f"{a:x}"# Hex, small letters
'2a'
>>> f"{a:X}"# Hex, capital letters
'2A'
>>> f"{a:c}"# ascii 码
'*'

Floating Point Number Formatting

>>> num_value = 223.456
>>> f'{num_value = :.2f}'
'num_value = 223.46'
>>> nested_format = ".2f"
>>> print(f'{num_value:{nested_format}}')
223.46

String Alignment

>>> x = 'test'
>>> f'{x:>10}' # Right alignment
'…

--

--

Responses (1)