F-string format string Python Overview

Transfer from  https://blog.csdn.net/sunxb10/article/details/81036693

 

Simple to use

f-string in braces  {} represents the field to be replaced, which is filled directly replace the contents:

 1 >>> name = 'Eric'
 2 >>> f'Hello, my name is {name}'
 3 'Hello, my name is Eric'
 4 
 5 >>> number = 7
 6 >>> f'My lucky number is {number}'
 7 'My lucky number is 7'
 8 
 9 >>> price = 19.99
10 >>> f'The price of this book is {price}'
11 'The price of this book is 19.99'
12 --------------------- 
13Disclaimer: This article is CSDN blogger original article "sunxb10", following the by-4.0 CC SA copyright agreement, reproduced, please attach the original source link and this statement.
14 Original link: https: //blog.csdn.net/sunxb10/article/details/81036693

 

 

Expression evaluation function call

f-string braces  {} can be filled expression or function call, Python will obtain a result and filled into the string returned:

 1 >>> f'A total number of {24 * 8 + 4}'
 2 'A total number of 196'
 3 
 4 >>> f'Complex number {(2 + 2j) / (2 - 3j)}'
 5 'Complex number (-0.15384615384615388+0.7692307692307692j)'
 6 
 7 >>> name = 'ERIC'
 8 >>> f'My name is {name.lower()}'
 9 'My name is eric'
10 
11 >>> import math
12 >>> f'{IS Math.log answer of The (Math.PI)} ' 
13 is  ' of The answer IS 1.1447298858494002 ' 
14 --------------------- 
 15 Copyright: This is CSDN bloggers original article "sunxb10", following the by-4.0 CC SA copyright agreement, reproduced, please attach the original source link and this statement.
16 Original link: https: //blog.csdn.net/sunxb10/article/details/81036693

 

 

Disclaimer: This article is a blogger original article, follow the CC 4.0 by-sa copyright agreement, reproduced, please attach the original source link and this statement. This link: https: //blog.csdn.net/sunxb10/article/details/81036693 Introduction f-string, also known as format string constant (formatted string literals), Python3.6 of string is newly introduced formatting method from PEP 498 - Literal string Interpolation, the main purpose is to make the operation more simple format string. f-string is in the form of F or f modifier lead string (f'xxx 'or F'xxx'), braces {} indicate the field to be replaced; f-string string is not in nature constant, but a calculation evaluated at runtime expression:
the while oTHER string a constant value for literals is Always have have, strings are formatted Really expressions eVALUATED external aT rUN time (unlike other string constant has a constant value, formatting characters. string actually seek operation runtime expression values) -. the Python Documentation
F-String is not inferior to conventional statements and str.format% -formatting () function in terms of functionality, but the performance is better than both simultaneously and using it is also more concise, so for Python3.6 and later recommended f-string for string formatting.
Usage This section mainly refer to the following information:
Python Documentation - Formatted String LiteralsPython Documentation - Format String SyntaxPEP 498 - Literal String InterpolationPython 3's f-Strings: An Improved String Formatting Syntax Advanced Use (Guide) python3 f-string format string Python 3: An Intro to f- strings simple f-string using braces {} represents a field to be replaced, which is filled directly replace the contents:
>>> name = 'Eric' >>> f'Hello, My name {name} iS '' the Hello, My name iS Eric '
>>> >>> Number = f'My. 7 Lucky Number Number {IS}' 'My Lucky Number IS. 7'
>>> >>> f'The. price = 19.99. price of the this Book. price {IS} '' of The price of this book is 19.99'1234567891011 expression evaluation function call f-string braces {} may be filled expression or function call, Python will obtain a result and filled into the string returned:
>>> {24 Total Number of f'A. 8 *} +. 4 '' A 196 Total Number of '
>>> 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 '
>>> >>> f'The answer IS Math Import {Math.log (Math. pi)} '' the answer is 1.1447298858494002'12345678910111213 quotes, braces and braces backslash f-string can not be used outside the braces quotes quotes delimiter conflict, the situation can be flexibly switched according to the 'and':
> >> f'I am { "Eric"} '' I am Eric '>>> f'I am {' Eric '}' File "<stdin>", line 1 f'I am { 'Eric'} '^ SyntaxError: invalid syntax1234567 If 'and' insufficient to meet the requirements, may be used '' 'and' '':
>>> F "of He {Said" the I'm Eric "}" File "<stdin>",. 1 Line 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
1234 mentioned above, f-string can not be used in braces \ escape, in fact not only that, f-string is simply not allowed within the braces \. If you do need \ should first containing \ contents represented by a variable, the variable name and then fill in the f-string braces: >>> F "NEWLINE: {the ord ( '\ n-')}" File " <stdin> ", line 1SyntaxError: F-String Not the include expression The Part A backslash The CAN >>> NEWLINE the ord = ( '\ n-') >>> f'newline: NEWLINE {} '' NEWLINE: a plurality of rows 10'1234567 f- stringf-string can be used for multi-line string:




>>> 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. "12345678910 custom format: alignment, width, symbol, zero padding, precision, etc. f-string using binary {content: format} string format is provided, wherein the content is Alternatively and fill the contents of the string, and the like may be variable, expression or function, format is format descriptor. Need not be specified when the default format {: format}, as shown in the example above {content} can be write-only.
Detailed syntax and meaning of format descriptors can be found in the official Python documentation, a brief introduction here in chronological order using the common format descriptor meaning and effect:
Align the relevant format descriptor format descriptor meaning and role of <Left (string default alignment)> right-aligned (Numerical default alignment) ^ centered digital symbol correlation format descriptor format descriptor meaning role + negative numbers preceded by a minus sign (-), positive number preceded by a plus sign (+) - before negative plus a negative sign (-), before the number of n without any symbols (default) (space) a minus sign before the negative (-), plus a number of space just before Note: only applies to the numeric type.
Digital display related Format Descriptor Format Descriptor meanings digital display switching effect # 1 Note: Only applies to the numeric type. Note 2: The effect of different values of # different types, the table below:
Numeric types without # (default) plus the difference between binary integer # '1111011''0b1111011' beginning whether 0b octal integer '173''0o173' beginning whether '123''123' no difference hexadecimal integer decimal integer 0o at the beginning (lower case letters) '7b''0x7b' 0x whether hexadecimal integer (in capital letters) '7B''0X7B' is displayed at the beginning of the width of the accuracy of the correlation 0X format descriptor format descriptor meanings specified action width integer width the width of the width specified width 0width integer, beginning with 0 to specify the higher width with zeros width.precision width specifies the width of an integer, integer precision specified display accuracy Note 1: 0width available for complex type and non-numeric type, for an integer of not width.precision Types of. As used f, precision specified when F, e, E% and the number of bits after the decimal point, for g and G: Note 2: width.precision used for different types of floating-point formats, meaning in a plurality of different precision specifies significant digits (+ digits before the decimal point of decimal places). Note 3: width.precision floating-point addition, a plurality of strings can also be used, only this time using precision meaning precision before the string characters.
Example:
>>> >>> f'a 123.456 A = {A IS: 8.2f} '' 123.46 IS A '{A >>> f'a IS: 08.2f}' 'IS 00,123.46 A' >>> F 'a is {a: 8.2e} ' 'a is 1.23e + 02' >>
>>> s = 'hello' >>> f 's is {s: 8s} '' s is hello '>>> f's is {s: 8.3s}' 's is hel' 1234567891011121314151617 thousands separator Related Format Descriptor format descriptor meaning effect, using, as used _ _ as the thousands separator thousands separator NOTE 1: if specified, or _, f-string does not use the thousands separator any this is the default setting. Note :, 2 only applies to floating point, and decimal integer complex: for floating point and a plurality of partition ,, only digits before the decimal point. Note 3: _ suitable for floating point, and a plurality of two, eight, ten, hexadecimal integer: for floating point and the plural, spaced _ only digits before the decimal point; for two, eight, hexadecimal integer, fixed from low to high every four insert a _ (decimal integer is inserted every three _ a).
Example:
>>> >>> f'a 1234567890.098765 A = {A IS: F} '' IS A 1234567890.098765 '{A >>> f'a IS:, F}' 'IS A 1,234,567,890.098765' >>> F ' IS A {A: _F} '' IS A 1_234_567_890.098765 '
>>> >>> f'b IS 1234567890 B = {B: _B}' 'IS 100_1001_1001_0110_0000_0010_1101_0010 B' {B >>> f'b IS: _O } ''
Meaning and Function Format Descriptor suitable variable type String Format string b s ordinary binary integer format the integer c character format, by converting the encoded unicode character corresponding to an integer d is an integer in decimal format Integer Integer Integer o octal x hexadecimal integer format integer format (lowercase) integer hexadecimal integer format X (uppercase) format integer e scientific notation to represent × 10 ^ e float, complex, integer (automatically converted to floating point numbers) and e is equivalent to E, but E represents × 10 ^ to floating point, complex, integer (automatically converted to floating point) f fixed point format, default precision (precision) floating-point number is 6, a plurality of integer (automatically converted to floating point) F and f equivalent, nan, and it will be replaced by NAN and INF inf floating point, complex, integer (automatically converted to floating point) g common format, a fraction with F, e large numbers with floating point, complex, integer (automatically converted to floating point) G and G is equivalent to, but a fractional number f., E float with large numbers, complex numbers, integers (automatically converted to floating point)% percentage format, digital automatic layout multiplied by 100 after f format, and add the suffix% Points, the integer (automatically converted to floating point) common special format type: datetime standard library format type for a given layout time information for DATE, time and datetime objects
Sample Format Descriptor Meaning% a week display (abbreviation) 'Sun'% A week (full name) 'Sunday'% w week (number, 0 Sunday, Saturday 6) '0'% u day of the week (number, 1 is Monday and 7 is Sunday) '7'% d day (numbers 0 to make up two) '07'% b month (abbreviated) 'Aug'% B month (full name) 'August '% m month (figures to make up two 0)' 08 '% y year (the last two digits, in order to make up two 0)' 14 '% Y in (full number, not zero padding)' 2014 '% H hours (24-hour, two complement 0) '23'% I hour (12-hour, two complement 0) '11'% p aM / PM 'PM'% M minutes (0 to two complement) '23'% S seconds (two to complement 0) '56'% f microseconds (0 to complement six) '553777'% zUTC offset (format ± HHMM [SS], the time zone is not specified is returned empty string) '1030 +'% by name, if the zone Z (not the empty string specified region) 'EST'% j of several days (three to complement the year 0) in '195'% U year the first few weeks (weeks of the year with the first Sunday as the week 0 to 0 make up two) the first few weeks of the year '27'% w (with the first weeks of the year on Monday as 0 weeks to make up two 0) in the first few weeks of the year '28'% V (full year included the first week of January 4 for the first week to make up two 0) '28 'comprehensive example >>> a = 1234 >>> f'a is { a: ^ # 10X} '# center, a width of 10 bit hexadecimal integer (capital letters), displays the prefix 0X' IS A 0X4D2 '
>>>

00 '--------------------- Disclaimer: This article is the original article CSDN bloggers "sunxb10", following the CC 4.0 by-sa copyright agreements, please attach a reprint the original source link and this statement. Original link: https: //blog.csdn.net/sunxb10/article/details/81036693


Guess you like

Origin www.cnblogs.com/allison-aichipingguo/p/11358049.html