Python string processing and file manipulation

Source: Internet
Author: User

1. Strip function

Strip is trim (crop) the spaces or characters on either side of the string. (Lstrip/rstrip)
Such as:
    • Space
'     ABCDBCYESORNOABCBACDD    'print

Abcdbcyesornoabcbacdd
    • Character
' ABCDBCYESORNOABCBACDD '   print thestring.strip ('abcd')     #去掉两端的abcd字符yesorno

Question: How to remove the middle space.

thestring = ' Hello python '

s =  '    Hello python   '= s.split ()Print " ". Join (strlist) Hellopython

2. Split

The cut string object is a list.

s =  'age:13, Name:chen, grade:70'= s.split (',' )print  strlist['age:13'  Name: Chen'  grade:70']

3. Join string Join function

s = ['a'' b'c'd '  'print'. Join (s)print' - ' . Join (s) abcda-b-c-d

4, String reversal

s ='python'PrintS[::-1]l=list (s) l.reverse ()PrintL#". Join (L) #注意reverse函数返回值是一个列表Print "'. Join (l) nohtyp['N','o','h','T','y','P']nohtyp

5. Read the data in the file (ReadLines ())

 FR = open (filename) 
NumberOfLines = Len (Fr.readlines ())          # Get the number of lines in the file
    Returnmat = Zeros ((numberoflines,3))     & nbsp;   #prepare Matrix to return
    classlabelvector = []                        #prepare Labels return   
   
    index = 0
    for line in Fr.readlines ():
        line = Line.strip ()
         listfromline = line.split (' \ t ')
        Returnmat[index,: ] = Listfromline[0:3]
        classlabelvector.append (int (listfromline[-1]) )
        Index + = 1

FR = open (filename) data=[inst.strip (). Split ('\ t' for in Fr.readlins ()]

2014-10-12

This content complies with CC3.0 Copyright Agreement, reprint Please specify: Turn self-study and excellent, think then pass

This article link address: Python string processing and file manipulation

Python string processing and file manipulation

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.