Python - f string tricks
Sử dụng lại tên biến
str_value = "hello,python coders"
print(f"{ str_value = }")
# str_value = 'hello,python coders'
Thay đổi output
num_value = 125
print(f"{num_value % 2 = }")
# num_value % 2 = 1
Thay đổi date
import datetime
today = datetime.date.today()
print(f"{today: %Y%m%d}")
#20211224
print(f"{today =: %Y%m%d}")
#today = 20211224
Kiểu 2/8/16 Hexadecimal
>>> 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 码
'*'
Thay đổi Floating Point Number
>>> num_value = 223.456
>>> f'{num_value = :.2f}'
'num_value = 223.46'
>>> nested_format = ".2f"
>>> print(f'{num_value:{nested_format}}')
223.46
Kiểu chuỗi string
>>> x = 'test'
>>> f'{x:>10}' # Right alignment
' test'
>>> f'{x:*<10}' # Left alignment
'test******'
>>> f'{x:=^10}'# Center
'===test==='
>>> x, n = 'test', 10
>>> f'{x:~^{n}}'# Center
'~~~test~~~'
Thay đổi format
class MyClass:
def __format__(self, format_spec) -> str:
print(f'MyClass __format__ called with {format_spec!r}')
return "MyClass()"
print(f'{MyClass():bala bala %%MYFORMAT%%}')
# Output
MyClass __format__ called with format_spec='bala bala %%MYFORMAT%%'
MyClass()
Special
>>> import timeit
>>> timeit.timeit("""name = "Tony"
age = 100
'%s is %s.' % (name, age)""", number = 10000)
# 0.0029884499333798885
>>> timeit.timeit("""name = "Tony"
age = 100
'{} is {}.'.format(name, age)""", number = 10000)
# 0.003444851143285632
>>> timeit.timeit("""name = "Tony"
age = 100
f'{name} is {age}.'""", number = 10000)
# 0.0018234248273074627