python按行读取文件 如何去掉换行符 “\n” 使用strip()函数去掉每行结束的\n
例如:
1)
for line in file.readlines():
line=line.strip('\n')
2)
#读取 ip地址文件 写入 ip_address 列表
ip_address = []
with open('ip.txt', 'r') as f1:
for ip in f1.readlines():
if ip != None:
# 从文件中读取行数据时,会带换行符,使用strip函数去掉 换行符后存入列表
ip_address.append(ip.strip("\n"))
f1.close()
strip()函数原型
声明:s为字符串,rm为要删除的字符序列
-
s.strip(rm) 删除s字符串中开头、结尾处,位于 rm删除序列的字符
-
s.lstrip(rm) 删除s字符串中开头处,位于 rm删除序列的字符
-
s.rstrip(rm) 删除s字符串中结尾处,位于 rm删除序列的字符
注意:
当rm为空时,默认删除空白符(包括’\n’, ‘\r’, ‘\t’, ’ ')
时间是个伟大的作者,必将给出完美的答案。
更多参考:
https://www.cnblogs.com/david-cloud/p/9289828.html
https://www.cnblogs.com/zb-ml/p/8926463.html
https://www.zhihu.com/question/41719623
https://www.cnblogs.com/hackpig/p/8215786.html
https://blog.csdn.net/zhuzuwei/article/details/77766173
https://www.jb51.net/article/175845.htm
https://www.cnblogs.com/learning-logs/p/12922069.html
https://blog.csdn.net/xidianbaby/article/details/87790422