python中strip()和split()的使用方法(学习笔记)

1.strip():用于移除字符串头、尾指定的字符(默认空格),不能删除中间部分的字符。

#未使用strip()
path=r"C:\Users\67539\Desktop\22\11.txt"
f=open(path,"r")
for line in f:        # 按行读取
    print(line)
f.close()

#结果
cat 22

airplane 23

dog 58

mug 86
###########################
#使用strip()
cat={}
f=open(path,"r")
for line in f:
    print(line.strip())
f.close()
#结果
cat 22
airplane 23
dog 58
mug 86

2.split():指定分隔符对字符串进行切片,返回分割后的字符串列表(默认为所有的空字符,包括空格,换行\n等)。

#使用split()
f=open(path,"r")
for line in f:
     print(line.split())
f.close()
#结果
['cat', '22']
['airplane', '23']
['dog', '58']
['mug', '86']

#strip()和split()一起使用。
f=open(path,"r")
for line in f:
     print(line.strip().split())
f.close()
#结果
['cat', '22']
['airplane', '23']
['dog', '58']
['mug', '86']

#利用strip()和split()生成字典。
f=open(path,"r")
for line in f:
    ls = line.strip().split()
    cat[ls[0]] = ls[1]          # 生成字典
print(cat)
f.close()
#结果
{'cat': '22', 'airplane': '23', 'dog': '58', 'mug': '86'}

你可能感兴趣的:(笔记)