How to manipulate Python strings

Source: Internet
Author: User

1, go to the space and special symbols

Copy the code code as Follows:

S.strip (). lstrip (). rstrip (', ')

2. Copying strings

Copy the code code as Follows:

#strcpy (sstr1,sstr2)

SSTR1 = ' strcpy '

SSTR2 = SStr1

SSTR1 = ' Strcpy2 '

Print SSTR2

3. Connection string

Copy the code code as Follows:

#strcat (sstr1,sstr2)

SSTR1 = ' strcat '

SSTR2 = ' Append '

SSTR1 + = SStr2

Print SSTR1

4. Find Characters

Copy the code code as Follows:

#strchr (sstr1,sstr2)

# < 0 for not found

SSTR1 = ' STRCHR '

SSTR2 = ' s '

NPos = Sstr1.index (sStr2)

Print NPos

5. Comparing strings

Copy the 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 the 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 the code code as Follows:

#strlen (sStr1)

SSTR1 = ' strlen '

Print Len (sStr1)

8. Converting uppercase and lowercase characters in strings

Copy the code code as Follows:

S.lower () #小写

S.upper () #大写

S.swapcase () #大小写互换

S.capitalize () #首字母大写

String.capwords (S) #这是模块中的方法. It separates S with the split () function, then uses capitalize () to capitalize the initial letter and merge it with join ().

#实例:

#strlwr (sStr1)

SSTR1 = ' jcstrlwr '

SSTR1 = Sstr1.upper ()

#sStr1 = Sstr1.lower ()

Print SSTR1

9. Append a string of the specified length

Copy the 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 the code code as Follows:

#strncmp (sstr1,sstr2,n)

SSTR1 = ' 12345 '

SSTR2 = ' 123BC '

n = 3

Print CMP (sstr1[0:n],sstr2[0:n])

11. Copy Characters of the specified length

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

Copy the 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 the 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 String

Copy the code code as Follows:

#strrev (sStr1)

SSTR1 = ' ABCDEFG '

SSTR1 = sstr1[::-1]

Print SSTR1

15. Find String

Copy the code code as Follows:

#strstr (sstr1,sstr2)

SSTR1 = ' ABCDEFG '

SSTR2 = ' CDE '

Print Sstr1.find (sStr2)

16. Split string

Copy the 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 the code code as Follows:

delimiter = ', '

MyList = [' Brazil ', ' Russia ', ' India ', ' China ']

Print Delimiter.join (mylist)

18, the implementation of Addslashes in PHP

Copy the code code as Follows:

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 S

Print Addslashes (s)

19. Display only letters and numbers

Copy the 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. Intercepting strings

Copy the 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 understand?

21. String alignment at output

Copy the code code as Follows:

S.ljust (width,[fillchar])

#输出width个字符, s left-aligned, insufficient parts are filled with fillchar, the default is a space.

S.rjust (width,[fillchar]) #右对齐

S.center (width, [fillchar]) #中间对齐

S.zfill (width) #把S变成width长, and right-aligned, less part with 0 complement

22. Search and Replace in string

Copy the code code as Follows:

S.find (substr, [start, [end]])

#返回S中出现substr的第一个字母的标号, Returns-1 If there is no substr in S. Start and End function is equivalent to searching in s[start:end]

S.index (substr, [start, [end]])

#与find () is the same, but 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, then return-1, that is, the first occurrence of 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 for replacing special characters

S.strip ([chars])

#把S中前后chars中有的字符全部去掉, It can be understood to replace 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

Copy the 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 that retains the row delimiter after each row is True.

S.join (seq) #把seq代表的序列-string sequence, connected by s

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

Copy the code code as Follows:

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 after the post-natal translation table, the S to translate, and the deletechars of the characters Deleted. 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

Copy the 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. 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, which is not a specific 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 the code code as Follows:

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 () #S中的字母是否全是小写

S.isupper () #S中的字母是否便是大写

S.istitle () #S是否是首字母大写的

27, the string type conversion function, These functions only in the string module has

Copy the code code as Follows:

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

How to manipulate Python strings

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.