Python string manipulation

Source: Internet
Author: User
1, go to the space and special symbols

S.strip () S.lstrip () S.rstrip () S.strip (). Lstrip (). Rstrip ()

declaration : S is a string, RM is a sequence of characters to be deleted

S.strip (RM) Remove the characters from the beginning and end of the s string in the RM delete sequence

S.lstrip (RM) Delete the character in the S string at the beginning of the RM delete sequence

S.rstrip (RM) Removes the character from the end of the S string that is located in the RM delete sequence

2. Copying strings

#strcpy (str1,str2) str1 = ' strcpy ' str2 = str1str1 = ' strcpy2 ' Print str2

3. Connection string

#strcat (str1,str2) str1 = ' strcat ' str2 = ' append ' str1 + = Str2print str1

4. Find characters

#strchr (STR1,STR2) # < 0 for not found str1 = ' strchr ' str2 = ' s ' nPos = Str1.index (str2) Print NPos

5. Comparing strings

#strcmp (str1,str2) str1 = ' strchr ' str2 = ' strch ' Print cmp (STR1,STR2)

6. Whether the scanned 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. Converting uppercase and lowercase characters in strings

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) 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 specified 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 a string with the specified characters

str1 = ' 12345 ' ch = ' r ' n = 3STR1 = n * ch + str1[3:]print str1

13. Scan string

#strpbrk (str1,str2) str1 = ' Cekjgdklab ' str2 = ' gka ' NPos = -1for C in str1:    if C in str2:        NPos = Str1.index (c)        b Reakprint NPos

14. Flip String

#strrev (str1) str1 = ' ABCDEFG ' str1 = Str1[::-1]print str1

15. Find string

#strstr (str1,str2) str1 = ' ABCDEFG ' str2 = ' cde ' Print str1.find (str2)

16. Split string

#strtok (str1,str2) str1 = ' Ab,cde,fgh,ijk ' str2 = ', ' str1 = Str1[str1.find (str2) + 1:]print str1# or s = ' Ab,cde,fgh,ijk ' Prin T (S.split (', '))

17. Connection string

delimiter = ', ' mylist = [' Brazil ', ' Russia ', ' India ', ' China ']print delimiter.join (mylist)

18, the implementation of addslashes in PHP

def addslashes (s):    d = {' ' ': ' \ \ ' ', ' ' ': ' \ \ ', '/': ' \\\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. 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. Intercepting strings

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. String alignment at output

S.ljust (Width,[fillchar]) #输出width个字符, s left-aligned, the insufficient portion is filled with Fillchar, the default is a space. S.rjust (Width,[fillchar]) #右对齐 s.center (width, [Fillchar]) #中间对齐 s.zfill (width) #把S变成width长, and right-aligned, with less than 0 complement

22. Search and Replace in string

S.find (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 S does not have substr then return-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, which defaults to 8

23. Segmentation and combination of strings

S.split ([Sep, [Maxsplit]]) #以sep为分隔符, 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 by s

24, the mapping of the string, this function contains two functions

The String.maketrans (from, to) #返回一个256个字符组成的翻译表, where 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 encoding and decoding functions

S.encode ([encoding,[errors]]) # Where encoding can have a variety of 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 string test, the judgment function, this kind of function is not in the string module, these functions return is the BOOL value

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, the String type conversion function, these functions only in the string module has

String.atoi (S[,base]) #base默认为10, if 0, then s can be 012 or 0x23 This form of string, if it is 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

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.