程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

6 Python f string tips and tricks

編輯:Python

Compared with traditional string formatting ,Python Of f-strings Provides a more readable 、 More concise and error free string formatting . They contain many useful functions , These functions will certainly come in handy in daily use . Let's take a look at some of them .

String interpolation

up to now , Most commonly used f The string function is string interpolation . All you need to do is enclose values or variables in curly braces ( {}) in , Then you can start .

str_val = 'apples'
num_val = 42
print(f'{num_val} {str_val}') # 42 apples

Variable name

In addition to getting the value of the variable , You can also get its name next to the value . This is particularly useful when debugging , And through = Add an equal sign after the variable name in curly braces ( ) Easy to finish .

please remember , Spaces in braces have been taken into account , Therefore, adding spaces around the equal sign can make the results more readable .

str_val = 'apples'
num_val = 42
print(f'{str_val=}, {num_val = }') # str_val='apples', num_val = 42

Mathematical operations

Syntactically different from variable names , You can also f Perform mathematical operations in a string . You can put mathematical expressions in curly braces , If you add an equal sign , You will get the expression and its result .

num_val = 42
print(f'{num_val % 2 = }') # num_val % 2 = 0

Printable representation

In addition to pure string interpolation , You may also want to get a printable representation of the value . Use this repr() The function is already easy to complete .!rf-strings By appending a To provide shorter Syntax .

str_val = 'apples'
print(f'{str_val!r}') # 'apples'

Digital format

Besides ,f-strings It can also be used to format - So... In the name f. To add formatting to a value , You can add colons ( :), Followed by the format specifier . If you also want to print the name of the variable , This can also be combined with the previous equal sign .

Numbers are a good candidate . for example , If you want to trim the value to two decimal places , You can use .2f Format specifier .

price_val = 6.12658
print(f'{price_val:.2f}') # 6.13

Date format

Last , Dates can also be formatted like numbers , Use format specifiers . As usual ,%Y Indicates the whole year ,%m It's the month , It's the month %d One of these days .

from datetime import datetime;
date_val = datetime.utcnow()
print(f'{date_val=:%Y-%m-%d}') # date_val=2021-07-09

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved