1. Strip function
Strip is trim (crop) the spaces or characters on either side of the string. (Lstrip/rstrip)
Such as:
' ABCDBCYESORNOABCBACDD 'print
Abcdbcyesornoabcbacdd
' 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