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

本文最后记录时间 2024-03-31
文章链接地址:
https://me.jinchuang.org/archives/405.html
本站文章除注明[转载|引用|来源],均为本站原创内容,转载前请注明出处
使用腾讯云CDN的SDK 用脚本去刷新URL缓存
pip 安装错误 Command "python setup.py egg_info" failed with error code
Linux命令行界面使用Python+Selenium+Chrome对网页截图
warnings.warn('Selenium support for PhantomJS has been deprecated, please use headless

UltraCompare v18.10 功能强大的文本对比软件

Linux下安装Zabbix 4.0版本

留言列表

  1. cindy
    Windows 10 Microsoft Edge
    中国天津电信 ◀网络运营商

    看到代码就头大。。。

    1. Awking
      Windows 10 Google Chrome
      中国上海电信 ◀网络运营商

      脑瓜子疼?‍♀️

留言

顶部