poiluy 发表于 2014-10-13 09:40:44

python字符串处理与文件操作

1、strip函数
strip是trim(裁剪)掉字符串两边的空格或字符。(lstrip/rstrip)
如:

    空格

theString = '    abcdbcyesornoabcbacdd    '
print theString.strip()

abcdbcyesornoabcbacdd

   字符

theString = 'abcdbcyesornoabcbacdd'
print theString.strip('abcd')   #去掉两端的abcd字符

yesorno

问题:如何去掉中间空格。

theString = '    hello python   '

s ='    hello python   '
strList = s.split()
print "".join(strList)

hellopython



2、split

切割字符串对象为列表。

s ='age:13, name:chen, grade:70'
strList = s.split(',')
print strList

['age:13', ' name:chen', ' grade:70']

3、join 字符串连接函数


s = ['a', 'b', 'c', 'd']
print ''.join(s)
print '-'.join(s)

abcd
a-b-c-d





4、字符串倒转


s = 'python'
print s[::-1]

l = list(s)
l.reverse()
print l#''.join(l)#注意reverse函数返回值是一个列表
print ''.join(l)

nohtyp
['n', 'o', 'h', 't', 'y', 'p']
nohtyp





5、读入文件中的数据(readlines())


  fr = open(filename)
  numberOfLines = len(fr.readlines())         #get the number of lines in the file
    returnMat = zeros((numberOfLines,3))      #prepare matrix to return
    classLabelVector = []                     #prepare labels return   
   
    index = 0
    for line in fr.readlines():
      line = line.strip()
      listFromLine = line.split('\t')
      returnMat = listFromLine
      classLabelVector.append(int(listFromLine[-1]))
      index += 1







fr = open(filename)
data=




页: [1]
查看完整版本: python字符串处理与文件操作