Common operations for python-strings

Source: Internet
Author: User

Python string operations commonly used operations, such as string substitution, deletion, interception, copying, connection, comparison, search, segmentation, etc., the need for friends can refer to.

1. Remove spaces
Str.strip (): Deletes the specified character on either side of the string, writes the specified character in parentheses, and defaults to NULL

>>> a= '   Hello   ' >>> b=a.strip () >>> print (b) Hello

Str.lstrip (): Deletes the specified character to the left of the string, writes the specified character in parentheses, and defaults to a space

>>> a= '   Hello   ' >>> b=a.lstrip () >>> print (b) Hello      #右边空格可能看的不是很明显

Str.rstrip (): Removes the specified character to the right of the string, and the default is a space

>>> a= '   Hello   ' >>> b=a.rstrip () >>> print (b)    Hello

2. Copying strings

>>> a= ' Hello World ' >>> b=a>>> print (A, b) Hello World Hello World

3. Connection string

+: Connect 2 strings >>> a= ' Hello ' >>> b= ' World ' >>> print (a+b) Hello World Note: This method is also called "the Evil Plus", Because using the plus sign to connect 2 strings calls the static function String_concat (register pystringobject *a, register pyobject * b), in this function will open a piece of memory that is the size of a+b and the storage unit, A b string is then copied in. If n strings are connected  then it will be very resource-intensive to open up n-1 memory. Str.join: Connect 2 strings, you can specify the connection symbol (about join, the reader can see some relevant information on their own) >>> a= ' Hello ' >>> b= ' # # # # ' >>> A.join (b) ' #hello #hello #hello # '

4. Finding strings 

#str. Index and Str.find function the same, except that the find () lookup failure returns 1, which does not affect the program's operation. Generally use find!=-1 or find>-1 as the judging condition. Str.index: Detects if substring contains substring str, can specify range a= ' Hello World ' >>> a.index (' l ') 2>>> A.index (' x ') Traceback (most Recent:  File "<pyshell#40>", line 1, in <module>    a.index (' x ') valueerror:substring not Foundstr.find: Detects if substring contains substring str, can specify range >>> a= ' Hello World ' >>> a.find (' l ') 2>>> a.find (' x ') -1

5. Comparing strings

STR.CMP: Compares two objects and returns an integer based on the result. x< Y, the return value is a negative number, and the value returned by X>y is positive.
#python3已经没有该方法, the official document reads:
The CMP () function should be treated as gone, and the __cmp__ () special method is no longer supported. Use __lt__ () for sorting, __eq__ () with __hash__ (), and other rich comparisons as needed. (If you really need the CMP () functionality, you could use the expression (a > B) – (a < b) as the equivalent for CM P (A, b).)
The main idea is that the CMP () function has "left", if you really need the CMP () function, you can use the expression (a > B)-(a < b) instead of CMP (a, a)

>>> a=100>>> b=80>>> cmp (A, B) 1

6. Whether to include the specified string

In |not->>> a= ' Hello World ' >>> ' hello ' in atrue>>> ' 123 ' not in Atrue

7. String length

str.len>>> a= ' Hello World ' >>> print (len (a)) 11

8. Letter case Conversion in string 

S.lower () #转换为小写 >>> a= ' Hello World ' >>> print (A.lower ()) Hello worlds.upper () #转换为大写 >>> a= ' Hello World ' >>> print (A.upper ()) Hello Worlds.swapcase () #大小写互换 >>> a= ' HELLO World ' >>> print (A.swapcase ()) Hello Worlds.capitalize () #首字母大写 >>> a= ' Hello World ' >>> print (a.capitalize ()) Hello World

9. Place the string in a central position to specify the length and character of the position

Str.center () >>> a= ' Hello World ' >>> print (A.center (+, ' * ')) **************hello world************* **

10. String statistics 

>>> a= ' Hello World ' >>> print (A.count (' L ')) 3

11. String test, judgment function, this kind of function is not in the string module, these functions return is 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 ()                          # are all whitespace characters and have at least one character s.islower ()                          #S中的字母是否全是小写 s.isupper ()                          #S中的字母是否便是大写 s.istitle ()                          #S是否是首字母大写的

12. String slicing 

str = ' 0123456789′print Str[0:3] #截取第一位到第三位的字符print str[:] #截取字符串的全部字符print str[6:] #截取第七个字符到结尾print str[:-3] # Intercept from the beginning to the third character before print str[2] #截取第三个字符print str[-1] #截取倒数第一个字符print str[::-1] #创造一个与原字符串顺序相反的字符串print str[-3:-1] # Intercept the character before the last third and last digit print str[-3:] #截取倒数第三位到结尾print str[:-5:-3] #逆序截取, intercept between the fifth and last digits of the penultimate number

It is emphasized here that 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.

 

Method:

Name = "My \tname is {name} and I am {year} old" Print (Name.capitalize ()) Print (Name.count ("a")) print (Name.center (50, "-")) Print (Name.endswith ("ex")) print (Name.expandtabs (tabsize=30)) print (Name[name.find ("name"):]) print (Name.format ( Name= ' Alex ', year=23) print (Name.format_map ({' name ': ' Alex ', ' Year ': ') ') print (' AbA '). Isalpha ()) print (' 1 a '. Isdecimal ()) print (' 1 a '. IsDigit ()) print (' A 1 a '. Isidentifier ()) # interpretation is not a valid identifier for print (' 33A '). IsNumeric ()) print (' My name is '. Istitle ()) print (' My name was '. Isprintable ()) # TTY file, drive FilePrint (' My name is ' . Isupper ()) print (' + '. Join ([' 1 ', ' 2 ', ' 3 ')) print (Name.ljust (+, ')) (Name.rjust ()) print (' Alex '. Lower ( ) Print (' Alex '. Upper ()) print (' \nalex '. Lstrip ()) print (' alex\n '. Rstrip ()) print (' alex\n '. Strip ()) p = str.ma Ketrans ("Abcdefli", ' [email protected] ') print ("Alex Li". Translate (p)) print (' Alex Li '. replace (' l ', ' l ', 1)) Print (' Alex Lil '. RFind (' l ')) print (' 1+2+3+4 '. Split (' \ n ')) print (' 1+2\n+3+4 '. splitlInes ()) print (' Alex li '. swapcase ()) print (' Lex Li '. Title ()) print (' Lex Li '. Zfill (50)) 

  

 

Common operations for 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.