Python's f-strings do more than you expect

王林
Release: 2023-04-18 19:22:03
forward
1094 people have browsed it

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'
Copy after login

2. Directly change the output result

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

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
Copy after login

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 码
'*'
Copy after login

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
Copy after login

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~~~'
>>>
Copy after login

7. Use !s, !r

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

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%%}')
Copy after login

The output is as follows:

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

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!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!