Python string common operation method, python string

Source: Internet
Author: User

Python string common operation method, python string

Common Operations for python string operations, such as replacement, deletion, interception, replication, connection, comparison, search, and splitting of strings. For more information, see.

1. Remove Spaces
Str. strip (): Delete the specified characters on both sides of the string. Write the specified characters in parentheses. The default value is space.

1 >>> a = 'hello' 2 >>> B = a. strip () 3 >>> print (B) 4 helloView Code

Str. lstrip (): Delete the specified character on the left of the string, and write the specified character into parentheses. The default character is space.

1 >>> a = 'hello' 2 >>> B = a. lstrip () 3 >>> print (B) 4 hello # spaces on the right may not be obviousView Code

Str. rstrip (): Delete the specified character on the right of the string. The default value is space.

1 >>> a = 'hello' 2 >>> B = a. rstrip () 3 >>> print (B) 4 helloView Code

 

2. Copy the string

1 >>> a = 'Hello world' 2 >>> B = a3 >>> print (a, B) 4 hello worldView Code

3. connection string

1 +: connect two strings. 2 >>> a = 'hello' 3 >>> B = 'World' 4 >>> print (a + B) 5 hello world 6 Note: This method is also called the "", because using the plus sign to connect two strings will call the static function string_concat (register PyStringObject * a, register PyObject * B ), in this function, we will open up a storage unit that is the sum of a + B memory, and then copy the and B strings. If n strings are connected, memory will be opened up for n-1 times, which is very resource-consuming. 7 8 str. join: connects two strings and can specify the join symbol (for join, you can view related information on your own) 9 >>> a = 'hello' 10 >>> B = '#### '11 >>>. join (B) 12' # hello #'View Code

4. Search for strings

1 # the str. index and str. find functions are the same. The difference is that if the find () search fails,-1 is returned and the program running is not affected. Find is generally used! =-1 or find>-1 as the judgment condition. 2 str. index: Check whether the string contains a substring 'str'. The value range is 3 a = 'Hello world' 4 >>>. index ('l') 5 2 6 >>>. index ('x') 7 Traceback (most recent call last): 8 File "<pyshell #40>", line 1, in <module> 9. index ('x') 10 ValueError: substring not found11 str. find: Check whether the string contains the substring 'str'. The value range is 12 13> a = 'Hello world' 14 >>>. find ('l') 15 216 >>>. find ('x') 17-1View Code

5. compare strings

Str. cmp: Compares two objects and returns an integer based on the result. X <Y, the return value is negative, and X> Y returns a positive number.
# This method is not available in python3. this is written in the official documentation:
The cmp () function shocould 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 cocould use the expression (a> B)-(a <B) as the equivalent for cmp (a, B ).)
The general idea is that the cmp () function has "Left". If you really need the cmp () function, you can use the expression (a> B)-(a <B) replace cmp (a, B)

1 >>> a = 1002 >>> B = 803 >>> cmp (a, B) 4 1View Code

6. whether to include the specified string

1 in | not in 2 >>> a = 'Hello world' 3 >>> 'hello' in a4 True5 >>> '20140901' not in a6 TrueView Code

7. String Length

1 str. len2 >>> a = 'Hello world' 3 >>> print (len (a) 4 11View Code

8. Convert uppercase and lowercase letters in a string

1 S. lower () # convert to lowercase 2 >>> a = 'Hello world' 3 >>> print (. lower () 4 hello world 5 6 S. upper () # convert to uppercase 7 >>> a = 'Hello world' 8 >>> print (. upper () 9 HELLO WORLD10 11 12 S. swapcase () # case-insensitive 13 >>> a = 'Hello world' 14 >>> print (. swapcase () 15 hELLO wORLD16 17 S. capitalize () # uppercase 18 >>> a = 'Hello world' 19 >>> print (. capitalize () 20 Hello worldView Code

9. You can specify the length and the two sides of the string in the center position.

1 str. center () 2 >>> a = 'Hello world' 3 >>> print (. center (40 ,'*')) 4 ************** hello world ***************View Code

10. String statistics

>>> a='hello world'>>> print(a.count('l'))3

11. Test and judge functions of strings. These functions are not in the string module. These functions return bool values.

1 S. startswith (prefix [, start [, end]) # whether to start with prefix for 2 S. endswith (suffix [, start [, end]) # end with suffix 3 S. isalnum () # whether it is all letters and numbers with at least one character of 4 S. isalpha () # whether it is all letters with at least one character of 5 S. isdigit () # whether it is all numbers with at least one character of 6 S. isspace () # whether it is all blank characters with at least one character 7 S. islower () # Whether the letters in S are all lowercase 8 S. isupper () # Whether the letters in S are uppercase 9 S. istitle () # whether S is capitalizedView Code

12. String Slicing

1 str = '000000' 2 print str [0: 3] # capture the first to third character 3 print str [:] # capture all characters of a string 4 print str [6:] # capture the seventh character to the end of 5 print str [: -3] # capture 6 print str [2] # capture the third character 7 print str [-1] # capture the first character 8 print str [: :-1] # create a string 9 print str [-3: -1] # truncate the character 10 print str [-3:] # truncate the last and last digits to the end of 11 print str [:-5: -3] # reverse truncation, intercept between the Fifth and third digitsView Code

It should be emphasized that the string object cannot be changed. That is to say, after creating a string in python, you cannot change a part of the character. After any of the above functions change the string, a new string is returned, and the original string is not changed. Please forgive me for anything wrong.

 

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.