Home  >  Article  >  Backend Development  >  Python's f-strings do more than you expect

Python's f-strings do more than you expect

王林
王林forward
2023-04-18 19:22:031171browse

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.

1. Too lazy to type the variable name again

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

2. Directly change the output result

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

3. Directly format the date

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

4. 2/8/16 hexadecimal output is really too simple

>>> 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 码
'*'

5. Format Convert floating point numbers

>>> num_value = 123.456
>>> f'{num_value = :.2f}' #保留 2 位小数
'num_value = 123.46'
>>> nested_format = ".2f" #可以作为变量
>>> print(f'{num_value:{nested_format}}')
123.46

6. String alignment, so easy!

>>> x = 'test'
>>> f'{x:>10}' # 右对齐,左边补空格
'test'
>>> f'{x:*<10}'# 左对齐,右边补*
'test******'
>>> f'{x:=^10}'# 居中,左右补=
'===test==='
>>> x, n = 'test', 10
>>> f'{x:~^{n}}' # 可以传入变量 n
'~~~test~~~'
>>>

7. Use !s, !r

>>> x = '中'
>>> f"{x!s}" # 相当于 str(x)
'中'
>>> f"{x!r}" # 相当于 repr(x)
"'中'"

8. Custom 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%%}')

The output is as follows:

MyClass __format__ called with format_spec='bala bala%%MYFORMAT%%'
MyClass()

Finally

Python’s f-string is very flexible and elegant, and it is also the most efficient string splicing method:

Python's f-strings do more than you expect

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!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete