Python string manipulation (cut/replace/find/split)


Python intercepts a string using the variable [head subscript: tail subscript] to intercept the corresponding string, where the subscript starts from 0 and can be a positive or negative number, and the subscript can be empty to indicate that the head or tail is taken .

# Example 1: String interception
str = '12345678'
print str[0:1]
>> 1    # Output str position 0 to the character before position 1
print str[1:6]   
>> 23456    # Output str position 1 start Characters before position 6
num = 18
str = '0000' + str(num) # Combine strings
print str[-5:]   # Output string right 5 bits
>> 00018

The Python replacement string uses the variable .replace("replaced content", "replaced content" [, times]), and the number of replacements can be empty, which means to replace all. It should be noted that after replacing the string with replace, it is only a temporary variable and needs to be reassigned to save.

# Example 2: String replacement
str = 'akakak'
str = str.replace('k',' 8') # Replace all k in the string with 8
print str
>> 'a8a8a8'   # Output the result

Python finds a string using the variable .find("what to find" [, start position, end position]), the start position and the end position, which indicate the range to be searched, and if it is empty, it means to find all. After finding it, the position will be returned, and the position will be counted from 0. If it is found, it will return -1.

# Example 3: String search
str = 'a,hello'
print str.find('hello') # Find the string hello in the string str
>> 2    # Output the result

Python uses the variable .split("split sign" [split times]) to split strings. The split times indicates the maximum number of splits, and if it is empty, it splits all.

Example 4: character split
str = 'a,b,c,d'
strlist = str.split(',') # Split str string with comma and save it to list
for value in strlist: # Loop output list value
    print value
>> a    # output
>> b
>> c
>> d

Related: Python string manipulation (cut/replace/find/split)