python中去掉readline() 的换行符
· 技术积累 · Python

python使用readline()时读出的内容把换行(\n)也带上了,这并不是我们想要的结果。

示例:

#文本 test.txt
111111
222222
333333
444444
555555
666666

#脚本 readtest.py
#!/usr/bin/python
f = open('test.txt','r')
for i in range(5):
    print(f.readline())

#执行脚本逐行读取结果
[root@localhost ~]# python readtest.py 
111111

222222

333333

444444

555555

去掉换行符:

#第一种
print(f.readline().strip())

#第二种
print(f.readline().split('\n')[0])

#第三种
print(f.readline().replace('\n',''))


#脚本执行的结果
[root@localhost ~]# python readtest.py 
111111
222222
333333
444444
555555

本文最后更新时间 2019-02-25
文章链接地址:https://me.jinchuang.org/archives/405.html
本站文章除注明[转载|引用|原文]出处外,均为本站原生内容,转载前请注明出处


留言列表

  1. cindy
    cindy Windows 10 Microsoft Edge · 天津市天津市 · 回复

    看到代码就头大。。。

    1. J.C
      J.C Windows 10 Google Chrome · 上海市上海市 · 回复

      脑瓜子疼?‍♀️

留言

顶部
您当前正在使用Internet Explorer浏览器访问本站,本站在此浏览器上兼容性较差
建议使用 Chrome, Firefox, or Edge浏览器访问本网站