- 1 basic string Operation
- 2 string formatting: Compact version
- Font color= "#000000" >2.1 with string format operator
- 2.2 format string template with string
- 3 string format: Full version
- 3.1 conversion specifier
- 3.2 simple conversion
- 3.3 field width and precision
- 3.4 symbol, align and 0 fill
- 4 string method
- 4.1 find
- 4.2 join
- 4.3 lower
- 4.4 Replace
- 4.5 split
- 4.6 strip
- 4.7 translate
1 Basic string Operations
- Description: String is also a sequence of one, so fragmentation, multiplication, index, length, maximum, minimum, judge membership can be applied to the string;
- Note: The string is immutable, so it cannot be assigned a value;
- Example
| The code is as follows |
Copy Code |
1: >>> mystr="Test string"
2: ' t '
3: traceback (most Recent call Last:
4: "<pyshell#1>" in <module>
5 : ' t '
6: typeerror' str 'object not support item assignment
7: >>> |
2String Formatting: Compact version
2.1 operator with string formatting
- Description: String formatting using the string format operator percent ( % ) implementation, on the left-hand side of the operator is formatted string, the right is the value you want to be formatted;
- Attention:
- Only tuples and dictionaries can be formatted into more than one value, and lists and other sequences are formatted as a value;
- A conversion specifier that marks where the conversion value needs to be inserted;
- If you want to output a percent semicolon in a formatted string, you need to use the %
- Example:
| The code is as follows |
Copy Code |
1:#一般格式化
2:>>> MyFormat ="Hello, my name is%s%s"
3:>>> name = (' Bill ',' Gunn ')4:>>>Print(MyFormat% name)5:Hello, my Name isBill Gunn6:>>>7:
8:#用列表格式化
9:>>> MyFormat =' Hello, my name is%s '
Ten:>>> name=[' Bill ',' Gunn ']One :>>>Print(MyFormat% name)A :Hello, my Name is[' Bill ',' Gunn ']:
:#打印浮点数
:>>>ImportMath:>>>Print("PI =%.5f"% pi):PI= 3.14159:
:#打印百分号
:>>>Print("%.2f%%"% 22.3):22.3%:>>> |
2.2Format strings with template of string
- Description: Replaces a variable in a Unix shell with the substitute method, replacing the $foo in the string template with the passed in parameter foo
- Example:
| The code is as follows |
Copy Code |
1:#从string模块中导入Template
2:>>> fromStringImportTemplate3:#创建模板
4:>>> MyFormat = Template ("My name is $name")5:#替换变量并打印
6:>>>Print(Myformat.substitute (name="Bill Gunn."))7:My Name isBill Gunn8:>>>9:
Ten:#输出美元符号的方法, enter two $ in the template
One :>>> MyTemplate = Template ("The price is $$ $price")A :>>> Mytemplate.substitute (price=100):' The price is $ '
:>>>:
:#如果参数与后面的字符串相连, you need to enclose it in curly braces.
:>>> fromStringImportTemplate:>>> MyTemplate = Template ("It ' s ${x}tastic!"):>>> Mytemplate.substitute (x=' Slum '):"It ' s slumtastic!"
:>>>:
To :#使用字典替换参数
:>>> MyTemplate = Template ("My $property is $value"):>>> name = {}Num:>>> name["Property"] ="Name"
:>>> name["Value"] ="Bill Gunn."
:>>> Mytemplate.substitute (name):' My name is Bill Gunn '
:>>>: |
3String formatting: Full version
- Description: The right-hand operand of the string format operator if it is a tuple, then each element in the tuple must have a corresponding escape specifier in the format string.
- Example:
| The code is as follows |
Copy Code |
1:>>> data =tuple(List("123"))2:>>> data3:(' 1 ',' 2 ',' 3 ')4:#格式化字符串中只有一个转义说明符, and there are three elements in the tuple, the conversion will complain
5:>>>Print(' data is%s '% data)6:Traceback (most recent call last):7:File"<pyshell#18>", Line 1, in<module>8: Print(' data is%s '% data)9:TypeError: not AllArguments converted during string formattingTen:#显示元组中的全部元素
One :>>>Print(' data is%s %s '%s '% data)A :Data is1 2 3:>>>: |
3.1Conversion descriptor
- Conversion descriptor
| Escape Descriptor |
meaning |
| D,i |
Signed decimal integer |
| O |
Octal with no sign |
| U |
Decimal with no sign |
| X |
hexadecimal with no symbol (lowercase) |
| X |
hexadecimal with no symbol (uppercase) |
| E |
Floating-point number of scientific counting method (lowercase) |
| E |
Floating-point numbers of scientific notation (uppercase) |
| F,f |
Decimal floating-point numbers |
| G |
If the exponent is greater than-4 or less than the precision, the same as E, otherwise the same as F |
| G |
If the exponent is greater than-4 or less than the precision, the same as E, otherwise the same as F |
| C |
Given (accept integer or single character string) |
| R |
String (convert any Python object using repr) |
| S |
String (convert any Python object using str) |
3.2 Simple conversion
- Example:
| The code is as follows |
Copy Code |
1: #十进制整数
2: Print ("The $%d" %)
3: is $
4:
5: #十六进制整数
6: Print ("Hex%x" %)
7: Hex C
8:
9: #八进制整数 print ("Oct%o" %)
: Oct
>>>
: |
3.3Field width and precision
- Description
- Field width: The minimum number of characters retained by the converted value;
- Field Precision: The number of decimal places that should be in the result after conversion;
- can use * as field width or precision
- Example:
| The code is as follows |
Copy Code |
1: #限制宽度
2: "%10f" % Math.PI
3: ' 3.141593 '
4:
5: #限制小数位数
6: "%5.2f" % Math.PI
7: ' 3.14 '
8:
9: #用星号限制宽度和精度, in the following example, the width is 10 and the precision is 5
. Ten: '%*.*s ' ' Adfasdfadsfasdfasdfasdf ')
One : ' Adfas '
A : >>>
: |
3.4symbols, alignment, and 0 padding
- Description
- 0: The width is not enough with the number 0 fill;
- Minus sign: Left alignment;
- PLUS sign: Signs are marked either as positive or negative
- Space: Fill with space when the width is not enough;
- Example:
| The code is as follows |
Copy Code |
1:#空白补0
2:>>>Print("%010f"% Math.PI)3:003.1415934:
5:#左对齐
6:>>>"%-10.2f"% Math.PI7:' 3.14 '
8:
9:#空白右对齐
Ten:>>>Print("% 5dn% 5d"% (123, 12))One :123A :12:
:#显示正负符号
:>>>Print("%+5dn%+5d"% (123,-123)):+123:-123:>>>: |
4String method
4.1 Find
- Description: Used to find substrings in long strings and, if found, returns the first occurrence of the substring on the left and no return-1, when looking, you can also specify the range to look for in long strings, providing the starting index and end index as the parameter for the lookup;
- Note: When looking, include the starting index position, but excluding the location of the end index;
- Example:
| code is as follows |
copy code |
1: >>> String.ascii_letters 2: ' abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz ' 3: >>> letters = string.ascii_letters 4: &G T;>> letters.find ( ' AB ' ) 5: 6: >> ;> letters.find ( ' X ' , 30,-1) 7: 8: >> ;> Letters.find ( "AB" , num) 9: 10: |
4.2Join
- Description: Concatenate the elements in the queue with strings, and the elements in the list must be strings;
- Example:
| code is as follows |
|
| 1: >> > data = list ( ' 123456 ' ) 2: >>> data 4: >>> "AB" . Join (data) 5: ' 1ab2ab3ab4ab5ab6 ' 6: >>> |
7:
4.3 lower
- Note: Converts the string to lowercase letters and returns, but the original string does not change;
- Example:
| code is as follows |
|
< Span class= "Linenr" > 1: >>> mystr= "ABCD" 2: >>> Mystr.lower () 3: ' ABCD ' 4: >>> mystr Span class= "Linenr" > 5: ' ABCD ' 6: >>> |
4.4 replace
- Description: Returns the string after which all occurrences have been replaced
- Example:
| The code is as follows |
Copy Code |
1: "My name is Geng Qi"
2: >>> mystr.replace ("Geng Qi""Bill Gunn")
3: ' My name is Bill Gunn '
4: >>> |
4.5 Split
- Description: Split the string into a sequence;
- Note: If you do not provide a delimiter, whitespace is treated as a separator;
- Example
| The code is as follows |
Copy Code |
#以加号为分割符 2: >>> MyStr = 1+2+3+4+5+6 3: >>> mystr.split ( ' + ' ) 4: [ ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , ' 5 ' , span> ' 6 ' ] 5: 6: #不提供分割符时, with whitespace as separator
7: >>> mystr =
"This is a test string"
8: >>> mystr.split ()
9: [
' This ' ,
' is ' ,
' a ' ,
' test ' ,
' string ' '
10: >>>
11:
|
4.6Strip
- Note: Remove both sides of the blank, you can also remove the specified characters;
- Example:
| The code is as follows |
Copy Code |
1: " asdfad adfasf asdf "
2: >>> mystr
3: ' Tasdfad adfasf asdf tt '
4: #去除空白符
5: >> > Mystr.strip ()
6: ' asdfad adfasf asdf '
7:
8: #去除指定字符
9: >>> Mystr.strip (' t ')
: ' tasdfad adfasf ' asdf '
One : a
: |
4.7Translate
- Description: Translate is a word substitution, you can replace multiple characters at the same time
- Example:
| code is as follows |
|
< Span class= "Linenr" > 1: >>> table = str . Maketrans ( ' CS ' , ' KZ ' ') Span class= "Linenr" > 2: >>> table 3: {115:122, 99:107} 4: >>> " please don t knock at my door! .
Translate (table) 5: "Pleaze don ' t Knokk at my door!" 6: |