Heim  >  Artikel  >  Backend-Entwicklung  >  Die F-Strings von Python leisten mehr als Sie erwarten

Die F-Strings von Python leisten mehr als Sie erwarten

王林
王林nach vorne
2023-04-18 19:22:031132Durchsuche

Die F-Strings von Python leisten mehr als Sie erwarten

Freunde, die Python gelernt haben, sollten wissen, dass F-Strings zum Formatieren der Ausgabe sehr praktisch sind. Ich denke, die Verwendungsmethode ist nichts anderes als print(f 'value = {Wert}‘, tatsächlich übertrifft F-Strings Ihre Erwartungen bei weitem. Lassen Sie uns heute die coolen Dinge klären, die es tun kann

1 Ich bin zu faul, den Variablennamen noch einmal einzugeben#. 🎜🎜#
str_value = "hello,python coders"
print(f"{ str_value = }")
# str_value = 'hello,python coders'

2. Ändern Sie direkt das Ausgabeergebnis

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

3. Formatieren Sie das Datum direkt

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

4. Die hexadezimale Ausgabe ist wahr Zu einfach

>>> 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. Formatieren Sie Gleitkommazahlen

>>> 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. Verwenden Sie !s, ! r

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

8, benutzerdefiniertes Format

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

Die Ausgabe ist wie folgt:

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

Finally

Pythons f- string ist sehr flexibel und elegant und auch die effizienteste Art, Strings zu verbinden:

In Zukunft wird die Formatierung von Strings f sein -string. Wenn Sie es nützlich finden, mögen Sie es bitte, schauen Sie es sich an und folgen Sie es. Vielen Dank für Ihre Unterstützung Die F-Strings von Python leisten mehr als Sie erwarten!

Das obige ist der detaillierte Inhalt vonDie F-Strings von Python leisten mehr als Sie erwarten. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Dieser Artikel ist reproduziert unter:51cto.com. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen