Python string operations (capture/replace/search/split)

Source: Internet
Author: User

Python uses the variable [header Subscript: tail subscript] to intercept the corresponding string. The subscript starts from 0 and can be a positive or negative number, the subscript can be null, indicating that the header or tail is obtained.

# Example 1: string truncation STR = '000000' print STR []> 1 # print STR []> 12345678 # output STR position 1 start to position 6 character num = 18str = '000000' + STR (Num) # merge string print STR [-5:] # output string right 5 digits> 00018

 

The replacement string in python uses the variable. Replace ("replaced content", "replaced content" [, times]). The replacement times can be null, indicating that all replicas are replaced. Note that the replacement string with replace is only a temporary variable and must be assigned a value to save it.

# Example 2: String replacement STR = 'akakak' STR = Str. replace ('k', '8') # Replace all K in the string with 8 print STR> 'a8a8a8 '# output result

 

Python searches for strings using variables. find ("content to be searched" [, start position, end position]), start position and end position, indicating the range to be searched. If it is null, it indicates searching for all. After searching, the system returns the position starting from 0. if it finds the position, the system returns-1.

# Example 3: string search str = 'a, hello' print Str. Find ('hello') # search string 'hello' in string 'str'> 2 # output result

 

The Python delimiter uses the variable. Split ("delimiter" [number of splits]). The number of splits indicates the maximum number of splits. If it is null, the splits all.

Example 4: Str = 'a, B, c, d' strlist = Str. split (',') # Use commas to separate the STR string and save it to the list for value in strlist: # print value> A # output result> B> C> d

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.