Overview of Python format string f-string (summary)

Time:2019-11-27

brief introduction

F-string, also known as formatted string literals, is a new string formatting method introduced in Python 3.6. This method originates from PEP 498 – literal string interpolation, and its main purpose is to make the operation of formatted string easier. F-string is in the form offorFModifier LED string(f'xxx'orF'xxx'), in braces{}Indicates the field to be replaced; f-string is not a string constant in nature, but an expression that evaluates at run time:

While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.
(unlike other string constants with constant values, a formatted string is actually an expression evaluated at run time.)
—— Python Documentation

F-string is no less functional than the traditional% – formatting statements andstr.format()Function, at the same time, its performance is better than the two, and its use is more concise. Therefore, for Python 3.6 and later versions, it is recommended to use f-string for string formatting.

usage

This part mainly refers to the following materials:

Python Documentation – Formatted String Literals

Python Documentation – Format String Syntax

PEP 498 – Literal String Interpolation

Python 3’s f-Strings: An Improved String Formatting Syntax (Guide)

Advanced use of Python 3 f-string format string

Python 3: An Intro to f-strings

Simple use

Braces for f-string{}Indicates the replaced field, where the replacement content is directly filled in:


>>> name = 'Eric'
>>> f'Hello, my name is {name}'
'Hello, my name is Eric'

>>> number = 7
>>> f'My lucky number is {number}'
'My lucky number is 7'

>>> price = 19.99
>>> f'The price of this book is {price}'
'The price of this book is 19.99'

Expression evaluation and function call

Braces for f-string{}You can fill in an expression or call a function. Python will find its result and fill it in the returned string:


>>> f'A total number of {24 * 8 + 4}'
'A total number of 196'

>>> f'Complex number {(2 + 2j) / (2 - 3j)}'
'Complex number (-0.15384615384615388+0.7692307692307692j)'

>>> name = 'ERIC'
>>> f'My name is {name.lower()}'
'My name is eric'

>>> import math
>>> f'The answer is {math.log(math.pi)}'
'The answer is 1.1447298858494002'

Quotes, braces, and backslashes

The quotation mark used in the f-string brace cannot conflict with the quotation mark delimiter outside the brace. You can switch flexibly according to the situation'and"


>>> f'I am {"Eric"}'
'I am Eric'
>>> f'I am {'Eric'}'
 File "<stdin>", line 1
  f'I am {'Eric'}'
        ^
SyntaxError: invalid syntax

if'and"Not enough to meet the requirements, it can also be used'''and"""


>>> f"He said {"I'm Eric"}"
 File "<stdin>", line 1
  f"He said {"I'm Eric"}"
        ^
SyntaxError: invalid syntax

>>> f'He said {"I'm Eric"}'
 File "<stdin>", line 1
  f'He said {"I'm Eric"}'
         ^
SyntaxError: invalid syntax

>>> f"""He said {"I'm Eric"}"""
"He said I'm Eric"
>>> f'''He said {"I'm Eric"}'''
"He said I'm Eric"

Quotation marks outside the braces can also be used\Escape, but cannot be used within braces\Escape:


>>> f'''He\'ll say {"I'm Eric"}'''
"He'll say I'm Eric"
>>> f'''He'll say {"I\'m Eric"}'''
 File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash

F-string braces if you need to show braces, enter two consecutive braces{{and}}


>>> f'5 {"{stars}"}'
'5 {stars}'
>>> f'{{5}} {"stars"}'
'{5} stars'

As mentioned above, f-string cannot be used within braces\Escape. In fact, it’s not only that. F-string is not allowed in braces at all\。 If it does\, you should first include\The content of is represented by a variable, and then the variable name is filled in the f-string brace:


>>> f"newline: {ord('\n')}"
 File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash

>>> newline = ord('\n')
>>> f'newline: {newline}'
'newline: 10'

Multiline f-string

F-string can also be used for multiline strings:


>>> name = 'Eric'
>>> age = 27
>>> f"Hello!" \
... f"I'm {name}." \
... f"I'm {age}."
"Hello!I'm Eric.I'm 27."
>>> f"""Hello!
...   I'm {name}.
...   I'm {age}."""
"Hello!\n  I'm Eric.\n  I'm 27."

Custom format: alignment, width, symbol, zero filling, precision, base, etc

F-string adopts{content:format}Format string, wherecontentIs to replace and fill in the contents of the string, which can be a variable, an expression, a function, etc,formatIs the format descriptor. You do not need to specify when using the default format{:format}, as shown in the above example, write only{content}Yes.

For the detailed syntax and meaning of format descriptors, please refer to the official Python documents. Here we briefly introduce the meaning and function of common format descriptors according to the order of use:

format descriptors Meaning and function
< Left alignment (string default alignment)
> Right alignment (default alignment of values)
^ Centered

Number symbol correlation format descriptor

format descriptors Meaning and function
+ Add a negative sign (-) before a negative number and a positive sign (+)
Minus sign (-) before negative number, no sign before positive number (default)
(space) Add a negative sign (-) before a negative number and a space before a positive number

Note: only for numeric types.

Format descriptor related to digital display mode

format descriptors Meaning and function
# Switch digital display mode

Note 1: only for numerical types.

Note 2:#The effect on different numerical types is different, as shown in the table below:

value type No addition#(default) plus# Difference
Binary integer '1111011' '0b1111011' Display at the beginning0b
Octal integer '173' '0o173' Display at the beginning0o
Decimal integer '123' '123' No difference
Hexadecimal integer (lowercase) '7b' '0x7b' Display at the beginning0x
Hexadecimal integer (uppercase) '7B' '0X7B' Display at the beginning0X

Width and precisionRelated format descriptor

format descriptors Meaning and function
width integerwidthSpecified width
0width integerwidthSpecify width, leading0Designated high level0Complement width
width.precision integerwidthSpecify width, integerprecisionSpecify display precision

Note 1:0widthNot available for complex and non numeric types,width.precisionNot available for integer types.
Note 2:width.precisionWhen used for floating-point numbers and complex numbers of different format types, they have different meanings: used forfFeEand%TimeprecisionSpecifies the number of digits after the decimal point forgandGTimeprecisionThe number of valid digits (before decimal point + after decimal point) is specified.
Note 3:width.precisionIn addition to floating-point numbers and complex numbers, it can also be used for stringsprecisionThe meaning is to use only the firstprecisionBit characters.

Example:


>>> a = 123.456
>>> f'a is {a:8.2f}'
'a is  123.46'
>>> f'a is {a:08.2f}'
'a is 00123.46'
>>> f'a is {a:8.2e}'
'a is 1.23e+02'
>>> f'a is {a:8.2%}'
'a is 12345.60%'
>>> f'a is {a:8.2g}'
'a is 1.2e+02'

>>> s = 'hello'
>>> f's is {s:8s}'
's is hello  '
>>> f's is {s:8.3s}'
's is hel   '

Thousand separator related format descriptor

format descriptors Meaning and function
, Use as thousands separator
_ Use UU as the thousands separator

Note 1: if not specified,or_, then f-string does not use any thousand separator, which is the default setting.
Note 2:,Floating point, complex and decimal integers only: for floating point and complex,,Only the digits before the decimal point are separated.
Note 3:_For floating-point numbers, complex numbers and binary, eight, ten, hexadecimal integers: for floating-point numbers and complex numbers,_Only the digits before the decimal point are separated; for binary, octal and hexadecimal integers, insert one every four digits from low to high_(decimal integers are inserted every three bits_)。

Example:


>>> a = 1234567890.098765
>>> f'a is {a:f}'
'a is 1234567890.098765'
>>> f'a is {a:,f}'
'a is 1,234,567,890.098765'
>>> f'a is {a:_f}'
'a is 1_234_567_890.098765'

>>> b = 1234567890
>>> f'b is {b:_b}'
'b is 100_1001_1001_0110_0000_0010_1101_0010'
>>> f'b is {b:_o}'
'b is 111_4540_1322'
>>> f'b is {b:_d}'
'b is 1_234_567_890'
>>> f'b is {b:_x}'
'b is 4996_02d2'

Format type dependent format descriptor

Basic format type

format descriptors Meaning and function Applicable variable type
s Normal string format Character string
b Binary integer format integer
c Character format, convert integer to corresponding character by Unicode encoding integer
d Decimal integer format integer
o Octal integer format integer
x Hexadecimal integer format (lowercase letters) integer
X Hexadecimal integer format (uppercase) integer
e Scientific counting format, ineExpress×10^ Floating point, complex, integer (automatically converted to floating point)
E AndeEquivalent, but withEExpress×10^ Floating point, complex, integer (automatically converted to floating point)
f Fixed point number format, default precision(precisionIt is 6 Floating point, complex, integer (automatically converted to floating point)
F AndfEquivalent, but willnanandinfchange intoNANandINF Floating point, complex, integer (automatically converted to floating point)
g General format, decimalfFor large numberse Floating point, complex, integer (automatically converted to floating point)
G AndGEquivalent, but decimalFFor large numbersE Floating point, complex, integer (automatically converted to floating point)
% Percentage format, number automatically multiplied by 100 and then pressfFormat layout, and add%Suffix Floating point, integer (automatically converted to floating point)

Common special format types: Standard LibrarydatetimeGiven format type for typesetting time information, applicable todatedatetimeandtimeobject

format descriptors Meaning Display example
%a Day of the week 'Sun'
%A Day of week (full name) 'Sunday'
%w Day of the week (number,0It’s Sunday.6It’s Saturday. '0'
%u Day of the week (number,1It’s Monday.7It’s Sunday. '7'
%d Day (number to0Make up for two) '07'
%b Month (abbreviation) 'Aug'
%B Month (full name) 'August'
%m Month (number to0Make up for two) '08'
%y Year (last two digits to0Make up for two) '14'
%Y Year (full number, no zeros) '2014'
%H Hour (24-hour system, to0Make up for two) '23'
%I Hour (12 hour system to0Make up for two) '11'
%p Am / PM 'PM'
%M Minutes0Make up for two) '23'
%S Seconds0Make up for two) '56'
%f Microseconds0Make up for six) '553777'
%z UTC offset (format is±HHMM[SS], if no time zone is specified, an empty string will be returned.) '+1030'
%Z Time zone name (empty string if no time zone is specified) 'EST'
%j The day of the year0Make up for three) '195'
%U Week of the year (week 0 after the first Sunday of the year0Make up for two) '27'
%w Week of the year (week 0 after the first Monday of the year0Make up for two) '28'
%V Week of the year (the first week of the year is the week containing January 4, and0Make up for two) '28'

Comprehensive example

>>> a = 1234
>>>F'a is {A: ^ාා10x} 'ාcenter, width 10 bits, hexadecimal integer (uppercase letter), display the 0xprefix
'a is  0X4D2  '

>>> b = 1234.5678
>>>F'b is {B: < 10.2f} 'ා left aligned, width 10 digits, display positive sign (+), fixed point number format, 2 decimal places
'b is +1234.57 '

>>> c = 12345678
>>>F'c is {C: 015, D} 'ාාාා񖓿ාhigh-order zero filling, width 15 bits, decimal integer, used as the thousandth division bit
'c is 000,012,345,678'

>>> d = 0.5 + 2.5j
>>>F'd is {D: 30.3e} 'ා width 30, scientific counting method, 3 decimal places
'd is      5.000e-01+2.500e+00j'

>>> import datetime
>>> e = datetime.datetime.today()
>>>F 'the time is {e:% Y -% m -% d (% a)% H:% m:% s}' ා datetime time time format
'the time is 2018-07-14 (Sat) 20:46:02'

lambda expressions

F-string braces can also be filled with lambda expressions, but the:F-string will be mistaken as the separator between expression and format descriptor. To avoid ambiguity, you need to put lambda expression in brackets()Internal:


>>> f'result is {lambda x: x ** 2 + 1 (2)}'
 File "<fstring>", line 1
  (lambda x)
       ^
SyntaxError: unexpected EOF while parsing

>>> f'result is {(lambda x: x ** 2 + 1) (2)}'
'result is 5'
>>> f'result is {(lambda x: x ** 2 + 1) (2):<+7.2f}'
'result is +5.00 '

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.

Recommended Today

Manjaro uses SS method (requires nodejs environment)

Just installed manjaro, need to installshadowsocks-qt5+Proxy SwitchyOmega, but the latest Chrome has long blocked the installation of non Google store CRX channels. Here is my solution, which is troublesome but usable. If you are familiar with NPM commands in nodejs, you won’t find it troublesome, because nodejs is used for compilation. Preparation environment: A VPS […]