[Switch] Python string operation implementation code (capture/replace/search/split), python string
Address: http://www.jb51.net/article/38102.htm
Ps: I haven't updated the python code for a long time. I used a string this time. Let's take a look.
Python uses the variable [header Subscript: tail subscript] to intercept the corresponding string. The subscript starts from 0 and can be a positive or negative number, the subscript can be null, indicating that the header or tail is obtained.
Copy the Code as follows:
# Example 1: String Truncation
Str = '000000'
Print str [0: 1]
> 1 # output str characters starting from 0 to before position 1
Print str [1: 6]
> 23456 # output str characters starting from position 1 to position 6
Num = 18
Str = '000000' + str (num) # merge strings
Print str [-5:] # The right five digits of the output string
> 00018
The replacement string in Python uses the variable. replace ("replaced content", "replaced content" [, times]). The replacement times can be null, indicating that all replicas are replaced. Note that the replacement string with replace is only a temporary variable and must be assigned a value to save it.
Copy the Code as follows:
# Example 2: String replacement
Str = 'akakakak'
Str = str. replace ('k', '8') # replace all k in the string with 8
Print str
> 'A8a8a8 '# output result
Python searches for strings using variables. find ("content to be searched" [, start position, end position]), start position and end position, indicating the range to be searched. If it is null, it indicates searching for all. After searching, the system returns the position starting from 0. if it finds the position, the system returns-1.
Copy the Code as follows:
# Example 3: string SEARCH
Str = 'a, hello'
Print str. find ('hello') # search for the string 'hello' in the string 'str'
> 2 # output results
The Python delimiter uses the variable. split ("delimiter" [number of splits]). The number of splits indicates the maximum number of splits. If it is null, the splits all.
Example 4: Character Segmentation
Copy the Code as follows:
Str = 'a, B, c, D'
Strlist = str. split (',') # Use commas to separate the str string and save it to the list.
For value in strlist: # cyclic output List value
Print value
> A # output result
> B
> C
> D