Python中如何去除换行符 您所在的位置:网站首页 word如何去除回车符和换行符 Python中如何去除换行符

Python中如何去除换行符

2024-01-05 23:18| 来源: 网络整理| 查看: 265

文章目录 方法1. exlude函数方法2. del d['\n']方法3. replace('\n', '')方法4:strip函数 Python中如何去除换行符 首先要了解’\\n’和’\n’的区别:

print("a\\nb") print("a\nb")

输出效果:

a\nb a b 方法1. exlude函数

exclude即排出的意思,include的反义词。 但在文本文件中使用exclude函数去除换行符时,其实无关紧要,\\n,\n皆可除。

fi = open("arrogant.txt","r") fo = open("PY301-1.txt","w") txt = fi.read() d = {} exclude = "! ? , . : ; \" \n -" # 写成\\n也可以 for line in txt: if line in exclude: continue else: d[line]=d.get(line,0)+1 ls =list(d.items()) print(ls)

因为在文本文件中实际上都是当作字符串’\n’去除的,这是第一种方法。

方法2. del d[‘\n’] fi = open("arrogant.txt","r") fo = open("PY301-1.txt","w") txt = fi.read() d = {} exclude = "! ? , . : ; \" -" for line in txt: if line in exclude: continue else: d[line]=d.get(line,0)+1 del d['\n']

当用字典来收集文本数据的时候,直接删除键即可。

方法3. replace(‘\n’, ‘’) fi = open("arrogant.txt","r") fo = open("PY301-1.txt","w") txt = fi.read() d = {} exclude = "! ? , . : ; \" -" for line in txt: line = line.replace("\n", "") # 直接替换成空 if line in exclude: continue else: d[line]=d.get(line,0)+1 方法4:strip函数 fi = open("arrogant.txt","r") fo = open("PY301-1.txt","w") txt = fi.read() d = {} exclude = "! ? , . : ; \" -" for line in txt: line = line.strip() if line in exclude: continue else: d[line]=d.get(line,0)+1

用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。 CSV中常用于删除数据换行符。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有