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[index,:] = listFromLine[0:3] classLabelVector.append(int(listFromLine[-1])) index += 1
fr = open(filename) data=[inst.strip().split(‘\t‘) for inst in fr.readlins()]
2014-10-12
本文内容遵从CC3.0版权协议,转载请注明:转自学而优,思则通
本文链接地址:python字符串处理与文件操作
时间: 2024-10-12 09:23:55