Python处理文本换行符

本文介绍了如何处理Python中文本文件的换行符问题。通过在print语句后使用end=''参数避免换行,或者利用strip()函数去除字符串行尾的换行符。此外,还提供了相关参考链接以供深入学习。
部署运行你感兴趣的模型镜像

源文件内容如下:
在这里插入图片描述
源文件每行后面都有回车,所以用下面输出时,中间会多了一行

>>> try:
    with open(r"C:\Users\Administrator\Desktop\20190506biji0.txt" ) as f :
        for line in f:
            print(line)
except FileNotFoundError:
    print("读取文件出错")

    
hello world

how are you?

I am fine

有两种方法处理:

1.print后面带 end=’’,表示不换行

>>> try:
    with open(r"C:\Users\Administrator\Desktop\20190506biji0.txt" ) as f :
        for line in f:
            print(line,end='')
except FileNotFoundError:
    print("读取文件出错")

    
hello world
how are you?
I am fine

2.用strip()函数去掉每一行的换行符

>>> try:
    with open(r"C:\Users\Administrator\Desktop\20190506biji0.txt" ) as f :
        for line in f:	
            line=line.strip('\n')
            print(line)
except FileNotFoundError:
    print("读取文件出错")

    
hello world
how are you?
I am fine

再者:

>>> x='''hello world
how are you?
I am fine'''
>>> x.strip('\n')
'hello world\nhow are you?\nI am fine'
>>> print(x,end='')
hello world
how are you?
I am fine
>>> print(x)
hello world
how are you?
I am fine

参考:
https://www.cnblogs.com/hjhsysu/p/5748776.html

您可能感兴趣的与本文相关的镜像

Python3.11

Python3.11

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值