String
You can use the (' or ') to create a string.
Creating a string is simple, as long as you assign a value to the variable.
For example:
Field= ' Hello '
Note: The string is immutable, so the string cannot be assigned a shard value
You can output two lines in the output statement
Print (' King of the Land Tiger \ \ Chicken Stew mushroom ')
C:\python\python.exe c:/python.py/yuanzu.py
King cover the ground tiger
Stewed chicken with mushrooms
Escape characters in Python
Escape Character Description
\ (at end of line) continuous row
\ \ backslash Symbol
\ ' Single quotation mark
\ "Double quotation marks
\a Bells
\b Backspace (Backspace) line
\e Escape
\000 Empty
\ nthe line break
\v Portrait tab
\ t Transverse tab
\ r Enter
\f Page Change
\oyy octal number, yy represents the character, such as \o12 for line break
\XYY hexadecimal number, yy represents the character, such as \x0 for line break
\other other characters output in normal format
String formatting
string format characters
The string format is implemented using the Operator percent sign (%).
% can also be used as a modulo operation (redundancy) operator.
For example:
Print (' hello,%s '% ' world ')
C:\python\python.exe c:/python.py/zifuchuan.py
Hello,world
A string to be formatted is placed on the left, and the value you want to format is placed on the right. The formatted value can be a string or a number.
In the example:
Print (' Xu Wei a few%s years old this year '%18 ')
C:\python\python.exe c:/python.py/zifuchuan.py
Xu Wei is 18 years old this year.
The%s portion of the formatted string, called the conversion specifier, marks the location where the conversion value needs to be placed, and the generic term is a placeholder.
The previous example s indicates that the value to the right of the percent sign is formatted as a string, and s refers to Str. If it is not a string, it is converted to a string using str.
string format characters
Symbol Description Symbol Description
%c format character and its ASCII code%f format floating-point numbers to specify precision values
%s formatted string%e floating-point numbers formatted with scientific notation
%d formatted integer%E function with%E, format floating-point numbers with scientific notation
%u formatted unsigned reshape%g%e and%f shorthand
%o Formatting unsigned octal numbers%G%f and%e
%x format unsigned hexadecimal number%p The address of the variable with hexadecimal number
%x format unsigned hexadecimal number (uppercase)
Example: Formatting integers with%d
Print (' Xu Wei a few%d years old this year '%18.9 ')
C:\python\python.exe c:/python.py/zifuchuan.py
Xu Wei is 18 years old this year.
Example: using%f to format floating-point numbers to specify exact values
Print (' pi value:%f '%3.14)
C:\python\python.exe c:/python.py/zifuchuan.py
Pi pi values are: 3.140000
Note: When using%f, if you do not specify a precision, the default
If you want to be accurate to two decimal places, you need to specify the
Print (' pi value:%.2f '%3.14)
C:\python\python.exe c:/python.py/zifuchuan.py
Pi pi values are: 3.14
Specify the precision in the format of a period plus the number of decimal places you want to keep, as%.2f in the previous example is to keep 2 decimal places
Solve a real problem, output a number similar to 1.23% (that is, the percentage)
A small example: the company's market capitalization this year rose by the year 1.23%\
Print (' The company's market capitalisation has risen last year:%.2f%% '%1.23)
C:\python\python.exe c:/python.py/zifuchuan.py
The company's market capitalisation this year has risen from a year earlier: 1.23%
The percent symbol in the character is the conversion specifier, and if you want to output% (percent), you need to format the character%, so you need to use percent.
For example:
Print (' Output percent:%s '% '% ')
C:\python\python.exe c:/python.py/zifuchuan.py
Output percent sign:%
String Formatting tuples
The right-click operand of the format operator can be an element.
If the operand is a tuple, each of these elements is individually formatted, and each value requires a corresponding conversion descriptor.
For example:
Print (' Today is%s month%s, we go out at night to eat%s, total cost%d yuan '% (' 8 ', ' 24 ', ' grilled fish ', 123))
C:\python\python.exe c:/python.py/zifuchuan.py
Today is August 24, we go out to eat grilled fish at night, altogether spent 123 yuan
In strings with multiple placeholders, you can use tuples to pass in multiple formatted values.
Note: If you need to convert a tuple to exist as part of a transformation expression, you must enclose it in parentheses, or you will get an error.
When you use a list or other sequence to represent a tuple, the sequence is interpreted as a value. Only tuples and dictionaries can format more than one value.
Basic Conversion Specifiers (the order of these items is very important)
% Character: The token conversion specifier begins.
Conversion flags (optional):-Indicates alignment; + indicates that the value is to be preceded by a positive sign; "" (white space character) to hold a space before a positive number, and 0 to indicate that the value of the conversion is not sufficient to fill.
The width of the minimum segment (optional): The converted string should have at least the width specified by the value. If it is *, the width is read from the tuple.
Point (.) followed by the precision value (optional): If it is followed by a real number, the precision value represents the digits after the decimal point, and if the string is converted, the number represents the width of the maximum field, and if it is *, the precision is converted from the tuple.
Simple conversion
For example:
Print (' How much money is spent at the mall today:%.2f '%12345.1537)
C:\python\python.exe c:/python.py/zifuchuan.py
How much did you spend on shopping today: 12345.15
Print (' Bought an apple 7PLUS spent $%d yuan. ') %7888)
C:\python\python.exe c:/python.py/zifuchuan.py
Bought an apple 7PLUS spent $7888 yuan.
Field width and precision
The conversion descriptor includes the field width and precision. The field width is the number of minimum characters that are retained for the converted value, and the precision is the number of decimal digits that should be included in the result of the number conversion or the maximum characters that the string converted value can contain.
For example:
#字段宽度为10
Print (' pi value:%10f '%3.141593)
C:\python\python.exe c:/python.py/zifuchuan.py
Pi pi values are: 3.141593
The string width is 10, the string occupies 8 spaces, and 2 are left.
#字段宽度为10
Print (' pi value:%10.2f '%3.141593)
C:\python\python.exe c:/python.py/zifuchuan.py
Pi pi values are: 3.1
The string width is 10, the string occupies 4 spaces, and 6 are left.
#打印出前字符串前5个
Print (' String precision get:%.5s '% (' du Yu Heng '))
C:\python\python.exe c:/python.py/zifuchuan.py
String precision acquisition: Du Yu
Field widths and precision are integers, separated by a dot (.) number. Two are optional parameters, if the accuracy is given, it must contain the dot number.
You can use * as the field width or precision (both can be used *), and values are read from the tuple.
For example:
Print (' Get string precision from tuple:%*.*s '% (10,5, ' Hello World ')
C:\python\python.exe c:/python.py/zifuchuan.py
Get string precision from tuples: Hello
Print (' Get string precision from tuple to 5:%.*s '% (5, ' Hello World ')
C:\python\python.exe c:/python.py/zifuchuan.py
Get string precision from tuple to 5:hello
You can use * as the field width or precision (both can be used), and values are read from the tuple.
Symbols, alignments, and 0 fills
You can place a "marked table" zero before the field width and precision to fill with 0.
For example:
Print (' pi value:%010.2f '%3.141593)
C:\python\python.exe c:/python.py/zifuchuan.py
Pi pi values are: 0000003.14
Use the minus sign to align the values
For example:
Print (' pi value:%-10.2f '%3.141593)
C:\python\python.exe c:/python.py/zifuchuan.py
The value of pi is: 3.14 #后面有6个空格可以使用光标检测
Extra space on the right side of the number when using the minus sign
Blank ("") indicates before positive numbers, plus spaces
For example:
Print ("%5d"%10) + ' \ n ' + ("%5d"%-10))
C:\python\python.exe c:/python.py/zifuchuan.py
10
-10
The previous operation can also be used to align negative numbers
Plus indicates whether a positive or negative number represents a symbol
For example:
Print (' width front:%+5d '%10) + ' \ n ' + (' width front plus minus:%+5d '%-10))
C:\python\python.exe c:/python.py/zifuchuan.py
Width in front of the Gaga number: +10
Width front plus minus:-10
The above example can also be used for numerical alignment.
String method
Find () method
The Find () method is used to detect whether the string includes substring str. If you specify the Beg (start) and end (end) ranges, the check is included within the specified range. Returns the index value if the substring is included; otherwise 1.
The syntax for the Find () method is as follows:
Str.find (Str,beg=0,end=len (String))
STR stands for the specified instrumented string, beg represents the start index, and the default is 0;end for the end index, which defaults to the length of the string. Returns the leftmost index of the location of the substring, and returns 1 if it is not found.
The Find () method demonstrates:
Field= ' Do it Now ' Print (Field.find (' does ')) print (Field.find (' Now ')) print (Field.find (' Python '))
C:\python\python.exe c:/python.py/zifuchuan.py
0
6
-1
Note: The string's Find method returns a Boolean value. If 0 is returned, it means that a substring was found at index 0.
The Find method can also accept parameters that represent the starting and ending points
For example:
Field= ' Do it Now ' print (' provides a starting 2 output index location of: ', Field.find (' It ', 2) ') print (' Provide starting point 5 output index location: ', Field.find (' It ', 5) ') print (' Provide start 0 and end 3 output index positions as: ', Field.find (' It ', 0,3)) print (' provide start 0 and end 5 Output index location: ', Field.find (' It ', 0,5) ') print (' Provide start 5 and end 10 output index positions as: ', Field.find (' It ', 5,10))
C:\python\python.exe c:/python.py/zifuchuan.py
Provides a starting point 2 output index position of: 3
Provides a starting point 5 output index position of:-1
Provides start 0 and end 3 output index positions of:-1
Provides start 0 and end 5 output index positions of: 3
Provides start 5 and end 10 output index positions of:-1
Finds whether a specified string exists within the specified range by using the start and end values.
Join () method
The join () method is used to concatenate the specified character of an element in a sequence into a new string.
The syntax for the join () method is as follows:
Str.join (Sequence)
STR stands for the specified retrieved string, sequence represents the sequence of elements to concatenate, and returns a new string resulting from the specified character in the concatenated sequence of elements.
The Join () method demonstrates:
field=[' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ']print (' with + connection string list: ', ' + '). Join (field))
C:\python\python.exe c:/python.py/zifuchuan.py
List of connection strings with +: 1+2+3+4+5
Connecting tuples
dirs= (' Home ', ' data ', ' tmp ') print (' Path: ', '/'. Join (dirs))
C:\python\python.exe c:/python.py/zifuchuan.py
Path: home/data/tmp
Note: The call to the join operation and the called object must both be strings, and any one that is not a string will be an error.
Lower () method
The lower () method is used to convert all uppercase letters in a string to lowercase.
The syntax for the lower () method is as follows:
Str.lower ()
STR stands for the specified retrieved string and does not require parameters. Returns the result of converting all uppercase strings in a string to lowercase strings.
The lower () method demonstrates:
Name= ' Duyuheng ' Print (' call lower get string: ', Name.lower ())
C:\python\python.exe c:/python.py/zifuchuan.py
Call lower to get the string: Duyuheng
If you want to find a substring in a string and ignore the case, you can also use the lower () method
For example:
Name= ' Duyuheng ' Print (Name.lower (). Find (' Yu '. Lower ()))
C:\python\python.exe c:/python.py/zifuchuan.py
2
Note: For English strings, the lower () method does not have a problem with processing, and it is generally used for non-English processing.
Upper () method
The upper () method is used to convert all lowercase in a string to uppercase.
The upper () method syntax is as follows:
Str.upper ()
STR stands for the specified retrieved string and does not require parameters. Returns the result of a lowercase letter string converted to an uppercase string.
The upper () method demonstrates:
Name= ' Duyuheng ' Print (' call upper get string: ', Name.upper ())
C:\python\python.exe c:/python.py/zifuchuan.py
Call upper to get the string: Duyuheng
If you want to find a substring in a string and ignore the case, you can also use the upper () method
For example:
Name= ' Duyuheng ' Print (Name.upper (). Find (' Yu '. Upper ()))
C:\python\python.exe c:/python.py/zifuchuan.py
2
Swapcase () method
The Swapcase () method is used to convert the uppercase and lowercase letters of a string, converting the upper case of a string to lowercase, to uppercase
The Swapcase () method syntax is as follows:
Str.swapcase ()
STR stands for the specified retrieved string and does not require parameters. Returns a new string that is generated when the result is a case-letter conversion.
The Swapcase () method demonstrates:
Name= ' du YU Heng ' Print (' original string: ', name) print (' string obtained after calling the Swapcase method: ', Name.swapcase ())
C:\python\python.exe c:/python.py/zifuchuan.py
Original string: Du YU Heng
String to get after calling the Swapcase method: DU yu HENG
Replace () method
The replace () method replaces the old string in the string with the new one, and if you specify the third parameter max, the number of replacements is Max times.
The replace () method syntax is as follows:
Str.replace (Old,new[,max])
STR stands for the specified retrieved string, the old represents the substring to be substituted, and new is the string that replaces the old substring, and Max represents the optional string, instead of the number of Max times. Returns a new string that is generated after replacing the old (older string) in the string with the new one, and if you specify 3 parameter max, the number of replacements is no more than Max times.
The Replace () method demonstrates:
field = ' Do it now,do right now ' Print (' original string: ', field) print (' New string: ', Field.replace (' Do ', ' Just do ')) print (' New string: ', Field.replace (' O ', ' Just ', 1)) Print (' New string: ', Field.replace (' O ', ' Just ', 2) ') Print (' New string: ', Field.replace (' O ', ' Just ', 3 ))
C:\python\python.exe c:/python.py/zifuchuan.py
Original string: Do it now,do right now
New string: Just do it now,just
New string: Djust it now,do right now
New string: Djust it njustw,do right now
New string: Djust it njustw,djust right now
When the 3rd argument is not specified, all matching words nonalphanumeric replaced; when the third character is specified, the substitution is made from left to right and the number of replacements is no more than the specified number of times.
Split () method
The split () method slices A string by specifying a delimiter, and if the parameter num has a specified value, it separates only the NUM child characters. is the inverse method of join, used to divide the string
The split () method syntax is as follows:
Str.split (st= "", Num=string.count (str))
STR represents the string specified for retrieval; St represents the delimiter, the default is a space; Num represents the number of splits. Returns a list of strings after the result is split.
The Split () method demonstrates:
field = ' Do it Now ' print (' string delimited after no delimiter: ', Field.split ()) ' Print (' string based on I delimited: ', field.split (' I ')) ' Print (' Based on O delimited string: ') , Field.split (' O ')) print (' string separated 1 times according to O: ', field.split (' O ', 1))
C:\python\python.exe c:/python.py/zifuchuan.py
A string separated by no delimiters: [' do ', ' it ', ' now ']
Based on I delimited string: [' do ', ' t now ']
Based on O delimited string: [' d ', ' It n ', ' W ']
String separated by O after 1 times: [' d ', ' it Now ']
If you do not provide a delimiter, the program will use all the spaces as delimiters.
During the operation, you can specify the number of delimiters and splits, and if you do not specify the number of splits, the matching characters are retrieved and separated from left to right, and the number of segments does not exceed the specified number of times.
If you do not specify a number of splits, all matching strings will be split.
Strip () method
The Strip () method method is used to remove the character (by default, a space) specified by the tail of the string.
The syntax for the Strip () method is as follows:
Str.strip ([chars])
The STR represents the string specified for the retrieved string, and chars represents the character that is specified for removing the substring, and returns the result as a new string generated by removing the characters specified by the end of the string.
The Strip () method demonstrates:
name = '----du Yu heng----' Print (' original string: ', name) print (' New string: ', Name.strip ('-')) ' st = '----du--yu--heng----' Print (' original string: ') , ST) Print (' New string: ', St.strip ('-'))
C:\python\python.exe c:/python.py/zifuchuan.py
Original string:----du Yu heng----
New string: Du Yu Heng
Original string:----Du--yu--heng----
New string: Du--yu--heng
As can be seen from the above example, the Strip () method refers to the removal of the tail-to-match characters, and the middle matching characters are not removed.
Translate () method
The translate () method converts the character of a string according to the table given by the parameter table (containing 256 characters), and the descriptors of the character to be filtered out is in the Del parameter.
The translate () method syntax is as follows:
Str.translate (Table[,deletechars]) STR stands for the specified retrieved string; Table represents the translation table, and the translation table is converted by Maketrans method Deletechars represents a list of characters to filter in a string. Returns the result as a translated string.
Translate () method demonstration (this is more difficult to understand);
Intab = ' Adfas ' outtab = ' 12345 ' Trantab = Str.maketrans (intab,outtab) st = ' Just do it ' print (' st Call translate method after: ', St.translate (Trantab))
C:\python\python.exe c:/python.py/zifuchuan.py
St Call translate method after: ju5t 2o it
Note: The first two Maketrans parameters must have the same length (the length of the Initab and Outtab values must be the same)
The translate () method and the Replace () method can replace some parts of the string.
The replace () method processes only a single character.
The advantage of the translate () method is that multiple substitutions can be made at the same time, sometimes much more efficient than the replace () method.
This article from "Duyuheng" blog, declined reprint!
Handbook of python3.5 cultivation 9