Python string manipulation real-way collection

Source: Internet
Author: User

Python string manipulation real-way collection, including almost all common python string operations, such as string substitution, deletion, interception, copying, connection, comparison, search, segmentation, etc., the need for Friends can refer to:

#1, go spaces and special symbols S.strip (). Lstrip (). Rstrip (', ') #2, copy string #strcpy (sstr1,sstr2) sStr1 = ' strcpy ' sStr2 = sstr1sstr1 = ' Strcpy2 ' Print sstr2#3, connection string #strcat (sstr1,sstr2) sStr1 = ' strcat ' sStr2 = ' append ' sStr1 + = Sstr2print sStr14, find character #strchr (SSTR1, SSTR2) # < 0 for not found sStr1 = ' strchr ' sStr2 = ' s ' nPos = Sstr1.index (sStr2) print npos#5, compare string #strcmp (sstr1,sstr2) sStr1 = ' Strc HR ' SSTR2 = ' strch ' Print cmp (SSTR1,SSTR2) 6, whether the scanned string contains the specified character #strspn (sstr1,sstr2) sStr1 = ' 12345678 ' sStr2 = ' 456 ' #sStr1 and Chars both in SStr1 and Sstr2print Len (SSTR1 and SStr2) #7, string length #strlen (sStr1) sStr1 = ' strlen ' Print len (sStr1) #8, case in string Convert S.lower () #小写 s.upper () #大写 s.swapcase () #大小写互换 s.capitalize () #首字母大写 string.capwords (S) #这是模块中的方法. It separates S with the split () function, then uses capitalize () to capitalize the first letter, and then merges it with join () #实例: #strlwr (sStr1) sStr1 = ' jcstrlwr ' sStr1 = Sstr1.upper () # SSTR1 = Sstr1.lower () print sStr1 #9, append string of specified length #strncat (sstr1,sstr2,n) sStr1 = ' 12345 ' sStr2 = ' abcdef ' n = 3sstr1 + = sstr2[0: N]print sstr1#10, String specified length comparison #strncmp (sstr1,sstr2,n) sStr1 = ' 12345 ' SSTR2 =' 123BC ' n = 3print cmp (sstr1[0:n],sstr2[0:n]) #11, copy characters of the specified length #strncpy (sstr1,sstr2,n) sStr1 = ' sStr2 = ' 12345 ' n = 3sstr1 = SSt R2[0:n]print sStr112, replaces the first n characters of a string with the specified character #strnset (sstr1,ch,n) sStr1 = ' 12345 ' ch = ' r ' n = 3SSTR1 = n * ch + sstr1[3:]print SSTR 1#13, scan string #strpbrk (sstr1,sstr2) sStr1 = ' Cekjgdklab ' sStr2 = ' gka ' NPos = -1for C in sstr1:if C in sstr2:npos = S Str1.index (c) Breakprint npos#14, flip string #strrev (sStr1) sStr1 = ' ABCDEFG ' sStr1 = Sstr1[::-1]print sStr115, find string #strstr ( SSTR1,SSTR2) sStr1 = ' ABCDEFG ' sStr2 = ' cde ' Print Sstr1.find (SSTR2) #16, split string #strtok (sstr1,sstr2) sStr1 = ' Ab,cde,fgh,ijk ' SSTR2 = ', ' sStr1 = Sstr1[sstr1.find (sStr2) + 1:]print sstr1# 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 de F Addslashes (s): D = {' ' ': ' \ \ ', ' ' ': ' \ \ ', '/': ' \\\0 ', ' \ \ ': ' \\\\ '} return '. Join (D.get (c, c) for C in s) s = "Joh N ' Johny ' Doe (a.k.a. \ "Super joe\") \\\0 "PrintSprint addslashes (s) #19, display only letters and numbers 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, intercept string str = ' 0123456789′print Str[0:3] #截取第一位到第三位的字符print str[:] #截取字符串的全部字符pri NT Str[6:] #截取第七个字符到结尾print str[:-3] #截取从头开始到倒数第三个字符之前print str[2] #截取第三个字符print str[-1] #截取倒数第一个字符print str[::-1] # Create a string opposite the original string print str[-3:-1] #截取倒数第三位与倒数第一位之前的字符print str[-3:] #截取倒数第三位到结尾print str[:-5:-3] #逆序截取, what do you mean? #21, the string is aligned at output s.ljust (Width,[fillchar]) #输出width个字符, S is left aligned, the insufficient portion is filled with Fillchar, and the default is a space. S.rjust (Width,[fillchar]) #右对齐 s.center (width, [Fillchar]) #中间对齐 s.zfill (width) #把S变成width长, and right-aligned, the less part with 0 to complement 22, Search and replace S.find in the string (substr, [Start, [end]]) #返回S中出现substr的第一个字母的标号, returns 1 if there is no substr in S. The start and end functions are equivalent to searching for S.index (substr, [Start, [end]) #与find () in S[start:end], except that when there is no substr in S, a run-time error is returned S.rfind (substr , [Start, [end]]) #返回S中最后出现的substr的第一个字母的标号, if there is no substr in SReturn-1, that is, the first occurrence of the substr from the right of the first letter marking S.rindex (substr, [Start, [end]]) S.count (substr, [Start, [end]]) #计算substr在S中出现的次数 S.replace (Oldstr, Newstr, [Count]) #把S中的oldstar替换为newstr, Count is the number of replacements. This is a common form of substitution, and there are some functions to replace s.strip ([chars]) with special characters #把S中前后chars中有的字符全部去掉, which can be understood as replacing S before and after chars to none S.lstrip ([chars]) S.rstrip ([ Chars]) S.expandtabs ([tabsize]) #把S中的tab字符替换没空格, each tab is replaced by a tabsize space, the default is 8 #23, the string is split and combined S.split ([Sep, [Maxsplit]]) # Take Sep as a delimiter and divide s into a list. Maxsplit represents the number of splits. The default delimiter is a white-space character s.rsplit ([Sep, [Maxsplit]]) s.splitlines ([keepends]) #把S按照行分割符分为一个list, and Keepends is a bool value, Row separators are preserved if they are true for each row. S.join (seq) #把seq代表的序列-string sequence, connected with S #24, the mapping of strings, this function contains two functions String.maketrans (from, to) #返回一个256个字符组成的翻译表, The characters from the from are converted to by one by one, so the from and to must be equal in length. S.translate (Table[,deletechars]) # Use the above function for the post-natal translation table, translate s for translation, and delete the characters in the Deletechars. It is important to note that if S is a Unicode string, then the Deletechars parameter is not supported, and the same functionality can be achieved by translating a character to none. You can also use the functionality of the codecs module to create more powerful translation tables. #25, String, and a pair of encoded and decoded functions S.encode ([encoding,[errors]) # Where encoding can have multiple values, such as gb2312 GBK gb18030 bz2 zlib big5 bzse64, etc. are supported. The default value for errors is "strict", which means unicodeerror. Possible values are ' ignore ', ' replace ', ' xmlcharrefreplace ', ' backslashreplace ' and all the values registered by Codecs.register_error. This section covers the codecs module, not the S.decode ([encoding,[errors]) #26, the test of strings, the judging function, which is not in the string module, these functions return bool values S.startswith (Prefix[,start[,end]]) #是否以prefix开头 S.endswith (Suffix[,start[,end]) #以suffix结尾 s.isalnum () #是否全是字母和数字, and has at least one character S.isalpha () #是否全是字母, and has at least one character s.isdigit () #是否全是数字, and has at least one character s.isspace () #是否全是空白字符, and has at least one character s.islower () # Whether the letters in S are all lowercase s.isupper () #S中的字母是否便是大写 s.istitle () #S是否是首字母大写的 #27, String type conversion functions, these functions only have String.atoi (S[,base]) in the string module # Base default is 10, if 0, then s can be 012 or 0x23 This form of string, if 16 then s can only be 0x23 or 0x12 this form of String String.atol (S[,base]) #转成long String.atof (s[ , base]) #转成float

  

Once again, the string object is immutable, meaning that you cannot change a part of the character after Python creates a string. Any of the above functions will return a new string after the string has been changed, and the original is not changed. In fact, this is also a workaround, you can use S=list (s) This function to change S into a single character as a member of the list, so you can use the s[3]= ' a ' method of changing the value, and then use s= "". Join (s) revert to a string

Python string manipulation real-way collection

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.