1. String merging and linking
Plus sign Merge
Join method Merge
2, multiply and slice
Line= ' * ' *30
Print (line)
>>******************************
Slice:
Consequence[start_index:end_index:step]
Represents the first element, the positive index position defaults to 0, and the negative index position defaults to-len (consequence)
End_index represents the last element object, the positive index position defaults to Len (consequence)-1; Negative index position defaults to 1
PrintStr[0:3]#Intercept first-to-third-digit charactersPrintstr[:]#truncate all characters of a stringPrintStr[6:]#Intercept the seventh character to the end of thePrintSTR[:-3]#intercept from the beginning to the third character before the third one does not includePrintSTR[2]#interception of the third characterPrintSTR[-1]#Intercept the first character of the countdownPrintSTR[::-1]#create a string opposite to the original string orderPrintSTR[-3:-1]#the characters preceding the last third to the last digit do not include the last digit of the penultimate character.PrintStr[-3:] Intercept the last third to the endPrintSTR[:-5:-3] Reverse Intercept
Three-string segmentation
Common split, with split, does not support multiple separators
A complex separation
R means no escaping, the delimiter can be, or, a space followed by 0 additional spaces, and then the pattern to split
Split (string[, Maxsplit]) | Re.split (Pattern, string[, Maxsplit]):
Returns a list after splitting a string by a substring that can be matched. The maxsplit is used to specify the maximum number of splits and does not specify that all will be split.
Import re
p = re.compile (R ' \d+ ')
Print p.split (' One1two2three3four4 ')
# # # output # #
# [' One ', ' one ', ' one ', ' three ', ' four ',
4. Handling of the beginning and end of a string
For example, find out what a file name begins with or ends with
Filename= ' trace.h '
Print (Filename.endwith (' h '))
>>true
Print (Filenam.startwith (' Trace '))
>>true
5. Finding and matching strings
General Search:
Finds a string inside a long string, returns the index of the string that contains it, or returns 1
Str.find (' xxxx ')
Complex matching:
Using Import re
6. Substitution of strings
Normal Replacement: Replace
Str.replace (' replaced ', ' replace ')
Complex replacements
Using regular matching Re.sub
7. Remove some characters from the string
Remove whitespace for text processing such as reading a line from a file, and then removing the spaces on each line, tab or line break
Line= ' Congratulations, you guessed it. '
Print (Line.strip ())
>>congratulations, you guessed it.
Note: The space inside the string cannot be removed , to remove the need to use the RE module
Complex text cleanup can take advantage of str.translate,
First build a conversion table, table is a translation table, indicating the ' t ' o ' turn into uppercase ' t ' o ',
Then remove ' 12345 ' from the Old_str, then the remaining strings are translated by the table.
Common python string handling