在python在处理字符串时,解析txt文本时,经常会遇到 strip()与 split()函数。
一、strip()删除开头或者结尾部分字符,常用于删除空白字符
声明:s为字符串,rm为要删除的字符序列
s.strip(rm) 删除s字符串中开头、结尾处,位于 rm删除序列的字符
s.lstrip(rm) 删除s字符串中开头处,位于 rm删除序列的字符
s.rstrip(rm) 删除s字符串中结尾处,位于 rm删除序列的字符
注意:
- 当rm为空时,默认删除空白符(包括’\n’, ‘\r’, ‘\t’, ’ ')
以下为输出实例
sting=' \t\n Love 1314 for zhu '
print(sting.strip())
#Love 1314 for zhu 删除开头和结尾的空字符, 包括'\n' '\t' '\r' ''
sting='Love 1314 for zhu Love'
print(sting.strip('Love'))
# 1314 for zhu 删除开头结尾的
print(sting.lstrip('Love'))
# 1314 for zhu Love 删除开头的
print(sting.rstrip('Love'))
#Love 1314 for zhu 删除结尾的
二、split(rm)方法 以’rm’为标志 把字符串进行分割
例如
sting='Love.1314.for.zhu'
print(sting.split('.'))
#['Love', '1314', 'for', 'zhu'] 以'.'为标志将字符串进行分割
print(sting.split('.',1))
#['Love', '1314.for.zhu'] 以'.'为标志将字符串进行分割,只分割一次
或者时解析网址时
sting='www.baidu.com'
print(sting.split('.'))
#输出['www', 'baidu', 'com']
三、在处理字符串时的应用
一个正则匹配的例子:
str="xxxxxxxxxxxx5 [50,0,50]>,xxxxxxxxxx"
lst = str.split("[")[1].split("]")[0].split(",")
print(lst)
#结果 ['50', '0', '50']
# [1]表示按‘[’分割后得到数组['xxxxxxxxxxxx5', 50,0,50]>,xxxxxxxxxx] 取下标为1的元素
四、再读取处理txt文件时
例如读取隐形眼镜数据集中的数据
fr=open('lenses.txt')
print(fr.readlines())
输出结果为['young\tmyope\tno\treduced\tno lenses\n', 'young\tmyope\tno\tnormal\tsoft\n'.....等]
lenses=[data.strip().split('\t') for data in fr.readlines()]
print(lenses)
输出结果为 [['young', 'myope', 'no', 'reduced', 'no lenses'], ['young', 'myope', 'no', 'normal', 'soft'],,,等]
readlines()方法读取整个文件所有行,保存在一个列表(list)变量中,每行作为一个元素,但读取大文件会比较占内存。data.strip().split(’\t’)去除每一个元素 [young\tmyope\tno\treduced\tno lenses\n] 的\n,然后以‘\t’分割