Home > Article > Backend Development > Python's f-strings do more than you expect
Friends who have studied Python should all know that f-strings is used to format output very conveniently. I think its use method is nothing more than print(f'value = { value }', in fact, f-strings far exceeds your expectations. Today, let’s sort out the cool things it can do.
str_value = "hello,python coders" print(f"{ str_value = }") # str_value = 'hello,python coders'
num_value = 123 print(f"{num_value % 2 = }") # num_value % 2 = 1
import datetime today = datetime.date.today() print(f"{today: %Y%m%d}") # 20211019 print(f"{today =: %Y%m%d}") # today = 20211019
>>> a = 42 >>> f"{a:b}" # 2进制 '101010' >>> f"{a:o}" # 8进制 '52' >>> f"{a:x}" # 16进制,小写字母 '2a' >>> f"{a:X}" # 16进制,大写字母 '2A' >>> f"{a:c}" # ascii 码 '*'
>>> num_value = 123.456 >>> f'{num_value = :.2f}' #保留 2 位小数 'num_value = 123.46' >>> nested_format = ".2f" #可以作为变量 >>> print(f'{num_value:{nested_format}}') 123.46
>>> x = 'test' >>> f'{x:>10}' # 右对齐,左边补空格 'test' >>> f'{x:*<10}'# 左对齐,右边补* 'test******' >>> f'{x:=^10}'# 居中,左右补= '===test===' >>> x, n = 'test', 10 >>> f'{x:~^{n}}' # 可以传入变量 n '~~~test~~~' >>>
>>> x = '中' >>> f"{x!s}" # 相当于 str(x) '中' >>> f"{x!r}" # 相当于 repr(x) "'中'"
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%%}')
The output is as follows:
MyClass __format__ called with format_spec='bala bala%%MYFORMAT%%' MyClass()
Python’s f-string is very flexible and elegant, and it is also the most efficient string splicing method:
In the future, the formatting of strings will be f-string. If you find it useful, please like, watch, and follow. Thank you for your support!
The above is the detailed content of Python's f-strings do more than you expect. For more information, please follow other related articles on the PHP Chinese website!