use print() Function can output a string to the screen . For the output string , We have many ways to control the string Format , If your python edition >=3.6, So highly recommended f character string (f-string).
Based on using :
f'something{var}'
Add... At the beginning of a normal string f, Then inside the string It can be used {var}
Mark ,{var}
Will be replaced with the value of the variable .
year = 2016
event = 'Referendum'
f'Results of the {
year} {
event}'
#'Results of the 2016 Referendum'
stay {} Add a format specifier after the variable in .
f'{ Variable : Format description symbol }'
Format specifiers have a lot of content , Here are just a few common examples , More details can be found in the appendix of this article .
:. length f
Controls the number of digits after the decimal point of a floating-point number :
n = 1.23456
f'{
n:.2f}'' # After the decimal point 2 position
#1.23
': length '
Set the minimum character width for this field , Commonly used for column alignment :
table = {
'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
print(f'{
name:10} ==> {
phone:10}')
Detailed format control characters in the document -Python Standard library - Text processing service -string in :string — Common string operations — Python 3.10.4 file
The appendix at the end of the article extracts some descriptions .
Use repr()
or str()
Function can convert a value to a string .
str()
Function returns a human readable value ,repr()
Then generate a value suitable for reading by the interpreter .
If there is no object that does not support the display results for people to read , str()
Return and repr()
The same value .
In general , Numbers 、 Values of structures such as lists or dictionaries , Using these two functions, the output is expressed in the same form .
String has two different forms .
# Let's get to the bottom of it , These two methods actually call the object's __repr__
and __str__
Method ( We'll talk about it later ).
str.rjust(width) Method to fill in the space on the left , Ensure the specified width , Achieve alignment .
Similar to that str.ljust(width) and str.center(width)
for x in range(1, 11):
print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
# Note use of 'end' on previous line
print(repr(x*x*x).rjust(4))
These methods do not write anything , Only one new string is returned , If the input string is too long , They don't truncate strings , But return as is .
% Operator ( Remainder operator )
% Operators can also be used for string formatting . Given 'string' % values
, be string
Medium %
The instance will have zero or more values
Element substitution . This operation is called string interpolation . for example :
str.format() f- String has already implemented its function , Don't say more .
print('We are the {} who say "{}!"'.format('knights', 'Ni'))
# Output : We are the knights who say "Ni!"
We first get the file object , Then call the read / write method of the file object , Finally, close the file object .
open()
Method returns a file object ( For reading and writing ). Usually use
open(filename, mode, encoding=None)
To call the method , Such as :
f = open('workfile', 'w', encoding="utf-8")
The first parameter is the filename . The second parameter is open mode ,''w‘ Indicates the write mode ,‘r’’ Indicates the read mode ,'a’ Indicates the append mode ,'r+' Read write mode ,‘b’ Represents the binary format .mode The default value is ’r’.
We usually read and write text files , Text files have some different encoding formats (encoding). If not specified , The default value is the default code of the operating system . because UTF-8 Is the current standard encoding format , So the general settings
encoding=“utf-8”.
When processing documents , In general use with
keyword , Sure Automatically shut down file .
Otherwise you need to use f.close() To manually shut down , Release file resources .
with open('workfile', encoding="utf-8") as f:
read_data = f.read()
# with After the block ends, the file will be automatically closed
f.closed
Suppose you already have a file object f.
f.read(size) read Take the contents of the file , Return string .size Optional indicates the maximum number of characters to read , Read the entire file by default when not writing .
f.readline() From file read take A single data , Line breaks are reserved at the end of the string .f.readline()
Returns an empty string , It means that the end of the file has been reached , Blank line use '\n'
Express , The string contains only one newline character .
f.readlines() In the form of a list read Take... From the file All right , It can be used list(f)
or f.readlines()
.
When reading multiple lines from a file , You can loop through the entire file object . This operation makes efficient use of memory , Fast , And the code is simple :
for line in f:
print(line, end='')
f.write(string)
hold string The content of Write Enter file , And returns the number of characters written .
f.tell()
Return integer , Gives the current location of the file object in the file , In binary mode, the number of bytes starting from the file , And numbers with unknown meaning in text mode .
f.seek(offset, whence)
You can change the location of file objects . By adding offset Calculation location ; The reference point is whence Parameter assignment . whence The value is 0 when , Means to calculate from the beginning of a file ,1 Indicates that the current file location is used ,2 Use the end of the file as a reference point . Omit whence when , The default value is 0, That is, the beginning of the file is used as the reference point .
json
Save structured data json The full name is JavaScript Object Notation(JavaScript Object notation ). Similar to dictionary format :
{
"sites": [
{
"name":" Novice tutorial " , "url":"www.runoob.com" },
{
"name":"google" , "url":"www.google.com" },
{
"name":" Microblogging " , "url":"www.weibo.com" }
]
}
json
The standard module adopts Python Data hierarchy , And convert it to string representation ; This process is called serializing ( serialize ). Reconstructing data from a string representation is called deserializing ( De sequencing ).
import json
x = [1, 'simple', 'list']
json.dumps(x)
If f It's the file object , You can use the following method to read and write in the file json Format data .( Of course ,f Yes, it is with open… The open )
json.dump(x, f) # Serialize to json Format
x = json.load(f) # To python Dictionary format
format_spec ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill ::= <any character>
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= digit+
grouping_option ::= "_" | ","
precision ::= digit+
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
explain :
fill
It's a fill in character
align
Is alignment
sign
It's a number symbol (±)
'#'
Options allow “ substitutive form ” Is used to perform the transformation . Alternative forms are defined for different types . This option applies only to integers 、 Floating point and plural types . For integer types , When using binary 、 Octal or hexadecimal output , This option adds the corresponding... To the output value '0b'
, '0o'
, '0x'
or '0X'
Prefix . For floating-point and complex types , The alternative form will make the conversion result always contain the decimal point symbol , Even if it does not have a decimal part . Usually only if there is a decimal part , The decimal point symbol... Appears only in the result of this kind of conversion . Besides , about 'g'
and 'G'
transformation , The last zero is not removed from the result .
width Is a decimal integer that defines the minimum total field width , Include any prefix 、 Delimiters and other formatting characters . If not specified , Then the field width will be determined by the content .
When alignment is not explicitly given , stay width Add a zero before the field ('0'
) Field will enable sign aware zero padding for numeric types . This is like setting fill The character is '0'
And alignment The type is '='
.
grouping_option in ','
Option means to use comma as thousands separator . For the separators set in the sensing area , Please switch to 'n'
Integer represents type .
'_'
Options represent floating-point representation types and integer representation types 'd'
Use underscore as thousands separator . For integer representation types 'b'
, 'o'
, 'x'
and 'X'
, Will be for each 4 Insert an underline into the first digit . Specifying this option for other presentation types will result in an error .
.precision, precision It's a decimal integer , Yes f'``F
Indicates how many digits should be displayed after the decimal point , about g``G
type , Indicates how many digits are displayed before and after the decimal point .
For string representation types , This field indicates the maximum field size - let me put it another way , The maximum number of characters . Integer representation types are not allowed to use precision .
type Determines how the data should be presented ( For example, base ).