Python string Manipulation Implementation code (intercept/replace/find/split)

Source: Internet
Author: User
Python intercepts the string using the variable [header subscript: tail subscript], you can intercept the corresponding string, where the subscript is starting from 0, can be positive or negative, subscript can be empty to take the head or tail.

# example 1: string intercept str = ' 12345678 ' Print str[0:1]>> 1   # output str position 0 start to position 1 characters before print Str[1:6]  >> 23456   # Output str position 1 start to position 6 characters before num = 18str = ' 0000 ' + str (num) # merge string print str[-5:]  # output string Right 5 bits >> 00018

The Python substitution string uses variables. replace ("replaced content", "replaced content" [, number of times]), and the number of replacements can be null, which means replace all. Note that replacing a string with replace is only a temporary variable and needs to be re-assigned to save.

# example 2: string substitution str = ' akakak ' str = str.replace (' k ', ' 8 ') # Replace all k in the string with 8print str>> ' a8a8a8 '  # output result

The Python lookup string uses variables. FIND ("What to Look for" [, start position, end position]), start and end position, indicate the range to look for, or null to find all. The location is returned after finding it, and the position is calculated from 0, and returns 1 if each is found.

# example 3: string Lookup str = ' A,hello ' Print str.find (' hello ') # Find string in string str hello>> 2   # output result

The Python split string uses a variable. Split ("split symbol" [Number of splits]), the number of splits indicates the maximum number of times, and the empty is split all.

Example 4: Character segmentation

str = ' a,b,c,d ' strlist = Str.split (', ') # splits the STR string with a comma and saves it to the list for value in Strlist: # loop Output list value    print value>> a   # output Results >> 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.