Python string operations (string replacement, deletion, interception, replication, connection, comparison, search, inclusion, case-insensitive conversion, and segmentation)
1. remove spaces and special symbols
s.strip()s.lstrip()s.rstrip()s.strip().lstrip().rstrip()
Statement: S is the string and rm is the sequence of characters to be deleted.
S. strip (rm) delete the characters starting and ending in the s string and located in the rm delete sequence
S. lstrip (rm) delete the characters starting from the s string in the rm delete sequence
S. rstrip (rm) deletes the characters at the end of the s string in the rm deletion sequence.
2. copy a string
#strcpy(str1,str2)str1 = 'strcpy'str2 = str1str1 = 'strcpy2'print str2
3. connection string
#strcat(str1,str2)str1 = 'strcat'str2 = 'append'str1 += str2print str1
4. search for characters
# Strchr (str1, str2) #<0 indicates that str1 = 'strchr' str2 = 'S' nPos = str1.index (str2) print nPos is not found
5. compare strings
#strcmp(str1,str2)str1 = 'strchr'str2 = 'strch'print cmp(str1,str2)
6. check whether the scan string contains the specified characters.
#strspn(str1,str2)str1 = '12345678'str2 = '456'#str1 and chars both in str1 and str2print len(str1 and str2)
7. string length
#strlen(str1)str1 = 'strlen'print len(str1)
8. convert the case in the string
S. lower () # lower case S. upper () # uppercase S. swapcase () # case-insensitive S. capitalize () # capital String. capwords (S) # This is a method in the module. It separates S with the split () function, converts the first letter into uppercase with capitalize (), and merges it with join () # instance: # strlwr (sStr1) str1 = 'jcstrlwr 'str1 = str1.upper () # str1 = str1.lower () print str1
9. append a string of the specified length
#strncat(str1,str2,n)str1 = '12345'str2 = 'abcdef'n = 3str1 += str2[0:n]print str1
10. string-specific length comparison
#strncmp(str1,str2,n)str1 = '12345'str2 = '123bc'n = 3print cmp(str1[0:n],str2[0:n])
11. Copy characters of the specified length
#strncpy(str1,str2,n)str1 = ''str2 = '12345'n = 3str1 = str2[0:n]print str1
12. replace the first n characters of the string with the specified characters.
str1 = '12345'ch = 'r'n = 3str1 = n * ch + str1[3:]print str1
13. scan strings
#strpbrk(str1,str2)str1 = 'cekjgdklab'str2 = 'gka'nPos = -1for c in str1: if c in str2: nPos = str1.index(c) breakprint nPos
14. flip string
#strrev(str1)str1 = 'abcdefg'str1 = str1[::-1]print str1
15. search for strings
#strstr(str1,str2)str1 = 'abcdefg'str2 = 'cde'print str1.find(str2)
16. split the string
# Strtok (str1, str2) str1 = 'AB, cde, fgh, ijk 'str2 =', 'str1 = str1 [str1.find (str2) + 1:] print str1 # or s = 'AB, cde, fgh, ijk' print (s. split (','))
17. connection string
delimiter = ','mylist = ['Brazil', 'Russia', 'India', 'China']print delimiter.join(mylist)
18. implementation of addslashes in PHP
def addslashes(s): d = {'"':'\\"', "'":"\\'", "\0":"\\\0", "\\":"\\\\"} return ''.join(d.get(c, c) for c in s)s = "John 'Johny' Doe (a.k.a. \"Super Joe\")\\\0"print sprint addslashes(s)
19. only letters and numbers are displayed.
def OnlyCharNum(s,oth=''): s2 = s.lower(); fomart = 'abcdefghijklmnopqrstuvwxyz0123456789' for c in s2: if not c in fomart: s = s.replace(c,''); return s;print(OnlyStr("a000 aa-b"))
20. truncate a string
str = '0123456789' str[0:3] str[:] str[6:] str[:-3] str[2] str[-1] str[::-1] str[-3:-1] str[-3:] str[:-5:-3]
21. alignment of strings in output
S. ljust (width, [fillchar]) # outputs width characters, and S is left aligned. fill the remaining parts with fillchar. the default value is space. S. rjust (width, [fillchar]) # right-aligned S. center (width, [fillchar]) # center alignment S. zfill (width) # Convert S to width length and align it on the right. fill in the missing part with 0.
22. search and replace strings
S. find (substr, [start, [end]) # return the number of the first letter of substr in S. if S does not contain substr, return-1. Start and end are equivalent to searching S in S [start: end. index (substr, [start, [end]) # is the same as find (), but if there is no substr in S, a runtime error S will be returned. rfind (substr, [start, [end]) # return the number of the first letter of the last substr in S. if S does not contain substr,-1 is returned, that is, the first character S of the substr that appears for the first time from the right side. rindex (substr, [start, [end]) S. count (substr, [start, [end]) # calculate the number of times that substr appears in S. replace (oldstr, newstr, [count]) # replace oldstar in S with newstr, and count with the number of replicas. This is a general form of replacement, and some functions replace S with special characters. strip ([chars]) # Remove all the characters in chars before and after S, which can be understood as replacing chars before and after S with None S. lstrip ([chars]) S. rstrip ([chars]) S. expandtabs ([tabsize]) # Replace the tab character in S with no space, and replace each tab with a tabsize space. the default value is 8.
23. string segmentation and combination
S. split ([sep, [maxsplit]) # Use sep as the separator to divide S into a list. Maxsplit indicates the number of splits. The default delimiter is the space character S. rsplit ([sep, [maxsplit]) S. splitlines ([keepends]) # divides S into a list based on the row delimiter. keepends is a bool value. if it is true, the row delimiter is retained. S. join (seq) # concatenates the sequence represented by seq, namely the string sequence, with S
24. string mapping. this function contains two functions.
String. maketrans (from, to) # returns a 256-character translation table, where the characters in from are converted to, so the from and to must be of the same length. S. translate (table [, deletechars]) # use the post-production translation table of the above function to translate S and delete some characters in deletechars. Note that if S is a unicode string, the deletechars parameter is not supported. you can translate a character into None to achieve the same function. In addition, you can use the functions of the codecs module to create more powerful translation tables.
25. a string also has a pair of encoding and decoding functions.
S. encode ([encoding, [errors]) # encoding can have multiple values, such as gb2312 gbk gb18030 bz2 zlib big5 bzse64. The default errors value is "strict", which means UnicodeError. Possible values include 'ignore', 'replace ', 'xmlcharrefresh', 'backslashreplace', and all values registered through codecs. register_error. This part of content involves the codecs module, not the extra white S. decode ([encoding, [errors])
26. test and judgment functions of strings. these functions are not in the string Module and return bool values.
S. startswith (prefix [, start [, end]) # whether to start with prefix S. endswith (suffix [, start [, end]) # end with suffix S. isalnum () # whether it is all letters and numbers with at least one character S. isalpha () # whether it is all letters with at least one character S. isdigit () # whether it is all numbers with at least one character S. isspace () # whether it is all blank characters with at least one character S. islower () # whether the letters in S are all lowercase S. isupper () # whether the letters in S are uppercase S. istitle () # whether S is capitalized
27. string type conversion functions. these functions are only available in the string Module.
String. atoi (s [, base]) # The default value of base is 10. if it is 0, s can be a string in the format of 012 or 0x23, if it is 16, s can only be a string in the format of 0x23 or 0X12. atol (s [, base]) # converts it to long string. atof (s [, base]) # converts it to float
Once again, the String object cannot be changed. that is to say, after creating a string in python, you cannot change a part of the character. After any of the above functions change the string, a new string is returned, and the original string is not changed. In fact, this is also a work und. you can use the S = list (S) function to change S to a list with a single character as a member, in this way, you can use S [3] = 'a' to change the value, and then use S = "". restore join (S) to a string
For more articles on Python string operations, please follow the Chinese PHP website!