Python string manipulation Method Encyclopedia _python

Source: Internet
Author: User
Tags strlen

1, to the space and special symbols

Copy Code code as follows:
S.strip (). Lstrip (). Rstrip (', ')

2. Copy String
Copy Code code as follows:
#strcpy (SSTR1,SSTR2)
SSTR1 = ' strcpy '
SSTR2 = SStr1
SSTR1 = ' Strcpy2 '
Print SSTR2

3. Connection string
Copy Code code as follows:
#strcat (SSTR1,SSTR2)
SSTR1 = ' strcat '
SSTR2 = ' Append '
SSTR1 + + SSTR2
Print SSTR1

4. Find characters
Copy Code code as follows:
#strchr (SSTR1,SSTR2)
# < 0 is not found
SSTR1 = ' STRCHR '
SSTR2 = ' s '
NPOs = Sstr1.index (SSTR2)
Print NPOs

5. Comparing Strings
Copy Code code as follows:
#strcmp (SSTR1,SSTR2)
SSTR1 = ' STRCHR '
SSTR2 = ' Strch '
Print CMP (SSTR1,SSTR2)

6. Whether the scanned string contains the specified characters
Copy Code code as follows:
#strspn (SSTR1,SSTR2)
SSTR1 = ' 12345678 '
SSTR2 = ' 456 '
#sStr1 and chars both in SSTR1 and SSTR2
Print Len (SSTR1 and SSTR2)

7, String length
Copy Code code as follows:
#strlen (SSTR1)
SSTR1 = ' strlen '
Print Len (SSTR1)

8. Convert uppercase and lowercase characters in a string
Copy Code code as follows:
S.lower () #小写
S.upper () #大写
S.swapcase () #大小写互换
S.capitalize () #首字母大写
String.capwords (S) #这是模块中的方法. It separates S with the split () function, and then uses capitalize () to capitalize the first letter, then merge it with join ().
#实例:
#strlwr (SSTR1)
SSTR1 = ' jcstrlwr '
SSTR1 = Sstr1.upper ()
#sStr1 = Sstr1.lower ()
Print SSTR1


9, append the specified length of the string
Copy Code code as follows:
#strncat (Sstr1,sstr2,n)
SSTR1 = ' 12345 '
SSTR2 = ' abcdef '
n = 3
SSTR1 + + sstr2[0:n]
Print SSTR1

10, string specified length comparison
Copy Code code as follows:
#strncmp (Sstr1,sstr2,n)
SSTR1 = ' 12345 '
SSTR2 = ' 123BC '
n = 3
Print CMP (Sstr1[0:n],sstr2[0:n])

11, copy the specified length of the characters
Copy Code code as follows:
#strncpy (Sstr1,sstr2,n)
SSTR1 = ' '
SSTR2 = ' 12345 '
n = 3
SSTR1 = Sstr2[0:n]
Print SSTR1

12. Replace the first n characters of the string with the specified characters
Copy Code code as follows:
#strnset (Sstr1,ch,n)
SSTR1 = ' 12345 '
ch = ' R '
n = 3
SSTR1 = n * ch + sstr1[3:]
Print SSTR1

13. Scan string
Copy Code code as follows:
#strpbrk (SSTR1,SSTR2)
SSTR1 = ' Cekjgdklab '
SSTR2 = ' Gka '
NPOs =-1
For C in SSTR1:
If C in SSTR2:
NPOs = Sstr1.index (c)
Break
Print NPOs

14, flip the string
Copy Code code as follows:
#strrev (SSTR1)
SSTR1 = ' ABCDEFG '
SSTR1 = Sstr1[::-1]
Print SSTR1

15. Find String
Copy Code code as follows:
#strstr (SSTR1,SSTR2)
SSTR1 = ' ABCDEFG '
SSTR2 = ' CDE '
Print Sstr1.find (SSTR2)

16. Split string
Copy Code code as follows:
#strtok (SSTR1,SSTR2)
SSTR1 = ' Ab,cde,fgh,ijk '
SSTR2 = ', '
SSTR1 = Sstr1[sstr1.find (SSTR2) + 1:]
Print SSTR1
#或者
s = ' Ab,cde,fgh,ijk '
Print (S.split (', '))

17. Connection string
Copy Code code as follows:
delimiter = ', '
MyList = [' Brazil ', ' Russia ', ' India ', ' ', ']
Print Delimiter.join (mylist)

18, the implementation of addslashes in PHP
Copy Code code as follows:
def addslashes (s):
D = {"': ' \ \", "'": "\ \", "C": "\\\0", "\": "\\\\"}
Return ". Join (D.get (c, c) for C in s)

s = "John ' Johny ' Doe" (a.k.a. \ "Super joe\") \\\0 "
Print S
Print Addslashes (s)

19. Show only letters and numbers
Copy Code code as follows:
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 the string
Copy Code code as follows:
str = ' 0123456789′
Print Str[0:3] #截取第一位到第三位的字符
Print str[:] #截取字符串的全部字符
Print Str[6:] #截取第七个字符到结尾
Print Str[:-3] #截取从头开始到倒数第三个字符之前
Print Str[2] #截取第三个字符
Print Str[-1] #截取倒数第一个字符
Print Str[::-1] #创造一个与原字符串顺序相反的字符串
Print Str[-3:-1] #截取倒数第三位与倒数第一位之前的字符
Print str[-3:] #截取倒数第三位到结尾
Print str[:-5:-3] #逆序截取, what do you mean, you don't get it?

21, the string in the output of the alignment
Copy Code code as follows:
S.ljust (Width,[fillchar])
#输出width个字符, S left alignment, less than the Fillchar fill, the default is a space.
S.rjust (Width,[fillchar]) #右对齐
S.center (width, [Fillchar]) #中间对齐
S.zfill (width) #把S变成width长, and in the right alignment, insufficient parts with 0 complement

22, search and replace in the string
Copy Code code as follows:
S.find (substr, [Start, [end]])
#返回S中出现substr的第一个字母的标号, if there is no substr in S, return-1. The start and end functions are equivalent to searching in s[start:end]
S.index (substr, [Start, [end]])
#与find () is the same, except 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 S, return-1, that is to say, the first letter of the substr that appears from the right.
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 substitutions. This is the general form of substitution and some functions for special character substitution
S.strip ([chars])
#把S中前后chars中有的字符全部去掉, it can be understood to replace s before and after chars with none
S.lstrip ([chars])
S.rstrip ([chars])
S.expandtabs ([tabsize])
#把S中的tab字符替换没空格, each tab is replaced with a tabsize space, and the default is 8

23, String segmentation and combination
Copy Code code as follows:
S.split ([Sep, [Maxsplit]])
#以sep为分隔符, divide s into a list. Maxsplit represents the number of splits. The default delimiter is a blank character
S.rsplit ([Sep, [Maxsplit]])
S.splitlines ([keepends])
#把S按照行分割符分为一个list, Keepends is a bool value, and if true, the row delimiter is preserved after each row.
S.join (seq) #把seq代表的序列--sequence of strings, connected with s

24, the mapping of the string, this function contains two functions
Copy Code code as follows:
String.maketrans (from, to)
#返回一个256个字符组成的翻译表, where the characters in the from are converted to "to" by one by one, so that from and to must be equal length.
S.translate (Table[,deletechars])
# Use the above function to translate the form after the Deletechars, and to delete some characters from it. Note that if S is a Unicode string, the Deletechars argument is not supported, and you can implement the same functionality in a way that translates a character to none. You can also use the features of the codecs module to create more powerful translation tables.

25, string and a pair of encoding and decoding functions
Copy Code code as follows:
S.encode ([encoding,[errors]])
# where encoding can have a variety of values, such as gb2312 GBK gb18030 bz2 zlib Big5 bzse64, etc. are supported. Errors The default value is "strict", meaning unicodeerror. Possible values are ' ignore ', ' replace ', ' xmlcharrefreplace ', ' backslashreplace ' and all the values registered through Codecs.register_error. This section covers the codecs module, not the special understanding
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
Copy Code code as follows:
S.startswith (Prefix[,start[,end]])
#是否以prefix开头
S.endswith (Suffix[,start[,end]])
#以suffix结尾
S.isalnum ()
#是否全是字母和数字, and 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 () #S中的字母是否全是小写
S.isupper () #S中的字母是否便是大写
S.istitle () #S是否是首字母大写的

27, the String type conversion function, these functions only in the string module has
Copy Code code as follows:
String.atoi (S[,base])
#base默认为10, if 0, then s can be 012 or 0x23 This form of string, if 16 then S is only 0x23 or 0x12 this form of string
String.atol (S[,base]) #转成long
String.atof (S[,base]) #转成float

Again, the string object is immutable, meaning you can't 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 source string has not changed. In fact, this is also a workaround, you can use the S=list (s) function to change S to 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

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.