Python string operation implementation code of interception and replace and find and segmentation
- 2020-04-02 13:10:34
- OfStack
Python intercepts strings by using a variable [header subscript: tail subscript], which intercepts the corresponding string, where the subscript starts at 0 and can be positive or negative, and the subscript can be null for the header or tail.
# case 1 : string interception
str = '12345678'
print str[0:1]
>> 1 # The output str location 0 Start to position 1 Previous character
print str[1:6]
>> 23456 # The output str location 1 Start to position 6 Previous character
num = 18
str = '0000' + str(num) # Merge string
print str[-5:] # Output string right 5 position
>> 00018
Python replaces strings with variables. Replace (" replaced content ", "replaced content "[, number of times]), and the number of times can be null. Note that the replace string is only temporary and needs to be re-assigned to save.
# case 2 : string replacement
str = 'akakak'
str = str.replace('k',' 8') # I'm going to put in the string k Replace them all with 8
print str
>> 'a8a8a8' # The output
Python USES variables to find strings. Find (" what to find "[, start position, end position]), start position and end position indicate the range to be found, and null indicates all. If found, the position will be returned, starting from 0. If found, the position will return -1.
# case 3 : string lookup
str = 'a,hello'
print str.find('hello') # In a string str Find a string in hello
>> 2 # The output
Python splits strings using variables. Split (" split token "[split number]), split number means the maximum number of split, is empty then split all.
Example 4: character segmentation
str = 'a,b,c,d'
strlist = str.split(',') # Split with a comma str String and save it to the list
for value in strlist: # The loop outputs the list values
print value
>> a # The output
>> b
>> c
>> d