Python Techniques for string handling

Source: Internet
Author: User

1. Using multiple characters or strings as separators to split a string

The Str.split () method can only make a single character or string as a delimiter, and the Re.split () method may use the regular expression as the delimiter, Re.split () is the same as the Str.split () return value type;

1 ' asdf fjdk; afed, FJEK,ASDF, foo ' 2 Import Re 3 >>> re.split (R'[;, \s]\s*', line)4# out : [' asdf ', ' fjdk ', ' afed ', ' Fjek ', ' asdf ', ' foo ']
2. Check whether the beginning or end is a specified string

Check the beginning of the string can be used Str.startswith (), the end can be used Str.endswith ();

1>>> filename ='Spam.txt'2>>> Filename.endswith ('. txt')3 #out:true4>>> Filename.startswith ('File:')5 #Out:false6>>> URL ='http://www.python.org'7>>> Url.startswith ('http:')8 #out:true

To match multiple possibilities, multiple matches can be packaged in tuples and then passed into the function;

1>>>ImportOS2>>> filenames = Os.listdir ('.')3>>>Filenames4 #Out : [' Makefile ', ' foo.c ', ' bar.py ', ' spam.c ', ' spam.h ']5>>> [Name forNameinchFilenamesifName.endswith (('. C','. h'))]6 #Out : [' foo.c ', ' spam.c ', ' spam.h '

You can also use slices to achieve, but it is not so elegant;

1 ' Spam.txt ' 2 ' . txt ' 3 # out:true

Match multiple suspicious uses or;

3. String substitution

Simple string substitution can be used:Str.repalce (), complex point with the sub () function in the RE module;

Python Techniques for string handling

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.