Python Removes Unwanted Characters from Strings
strip() in python removes the first and last specified characters
If the parameter ①() is empty, it will remove the first and last \r, \t, \n, space and other characters in the ss string by default;
② but can only delete the first and last specified characters in the string, the middle can not be deleted, you need to delete the characters in the middle, look down.
ss = '\n\n I'm me, \n you're you\n\n\n' print(ss) print("*"*15) print(('\n')) The results of the run are as follows: I'm me., You're you. *************** I'm me., You're you.
Using python's built-in replace() function
① denotes substitution and also allows the replacement of specified characters within a string.
② replace (old, new[,max]), old is the original string of characters, new is the need to replace the new string, max is the maximum number of matches, matching from left to right at most max times. In general, do not set the value of max, the default replacement of all.
ss = '\n\n I am me\t\n, \n you are you\n\n\n\n' print(ss) print("*"*15) print(('\n', '')) print(('\n', '&')) The results of the run are as follows: I'm me. , You're you. *************** I'm me.,You're you. &&I'm me.&,&You're you.&&&
Index slice deletes specified content
Index slicing does not change the original string, it just regenerates a new one.
ss = "I'm me, you're you. print(ss) print("*"*15) print(ss[:1] + ss[2:]) print(ss[:5] + ss[6:]) running result: I'm me.,You're you. *************** I, I, I, I, I, I, I, I, I, I, I, I,You're you. I'm me.,you you
Regular sub method replacement
import re s = '\n I'm me\t\n, \n you're you\n' print(s) print("*"*15) print(('[\t\n]', '')) print(('[\n]', '', s)) running result: I'm me. , You're you. *************** I'm me.,You're you.
Python translate() method
Converts the characters of the string according to the table (containing 256 characters) given by the parameter table, and the characters to be filtered out are put into the del parameter.
(table[, deletechars]); table – translation table,translation table是通过maketransMethods converted from。 deletechars – List of characters in the string to filter。 (intab, outtab) intab – String consisting of the characters to be replaced in the string。 outtab – String of corresponding mapped characters。
Python removes strings (removes the first few or the last few)
a = "16541616584984" a = a[2:-2] print(a)
Output results:
5416165849
a[2:-2] means remove the first two and the next two.
If the light removes the trailing a[:-2]
Remove the previous operation and so on 。。。。
summarize
The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.