搜索
首页后端开发Python教程python如何去除字符串最后的换行符‘\n’

python去除字符串最后的换行符‘\n’

s = s.replace('\n','').replace('\r','')

例子
取出gt.txt中的abcd等按顺序生成字典{‘0’:‘abcd’,‘1’:‘efg’},一般最后一个数据会有换行符需要去掉

gt.txt:
abcd xxx
efg xxx …

f = open('I:\\data_3\\gt.txt', 'r', encoding = 'UTF-8')
labelstr = f.readlines()
a = range(0,200)
index = [str(i) for i in a]
txt = [label.split(' ')[0].replace('\n','').replace('\r','') for label in labelstr]
labeldic = dict(zip(index, txt))

附录:在 Python 中从字符串中删除换行符可以使用哪些方式?

Python 中的字符串可以定义为用单引号或双引号括起来的 Unicode 字符簇。

与其他流行的编程语言一样,Python 也有一个由 \n 表示的换行符。它主要用于跟踪一行的顶点和字符串中新行的出现。

换行符也可以在 f 字符串中使用。此外,根据 Python 文档,print 语句默认在字符串末尾添加换行符。

接下来我们介绍几种在 Python 中从字符串中删除换行符的不同方法。

一、在 Python 中使用 strip() 函数从字符串中删除换行符

strip() 函数用于从正在操作的字符串中删除尾随和前导换行符。它还删除字符串两侧的空格。

以下代码使用 strip() 函数从 Python 中的字符串中删除换行符。

str1 = "\n Starbucks has the best coffee \n"
newstr = str1.strip()
print(newstr)

输出:

Starbucks has the best coffee

如果只需要删除尾随的换行符,可以使用 rstrip() 函数代替 strip 函数。前导换行符不受此函数影响并保持原样。

以下代码使用 rstrip() 函数从 Python 中的字符串中删除换行符。

str1 = "\n Starbucks has the best coffee \n"
newstr = str1.rstrip()
print(newstr)

输出:

Starbucks has the best coffee

二、在 Python 中使用 replace() 函数从字符串中删除换行符

也称为蛮力方法,它使用for循环和replace()函数。我们在字符串中寻找换行符\n作为字符串,并在for循环的帮助下从每个字符串中手动替换它。

我们使用字符串列表并在其上实现此方法。列表是 Python 中提供的四种内置数据类型之一,可用于在单个变量中存储多个项目。

以下代码使用 replace() 函数从 Python 中的字符串中删除换行符。

list1 = ["Starbucks\n", "has the \nbest", "coffee\n\n "]
rez = []
for x in list1:
    rez.append(x.replace("\n", ""))

print("New list : " + str(rez))

输出:

New list : ['Starbucks', 'has the best', 'coffee ']

三、在 Python 中使用 re.sub() 函数从字符串中删除换行符

re 模块需要导入到 python 代码中才能使用 re.sub() 函数

re 模块是 Python 中的内置模块,用于处理正则表达式。它有助于执行在给定的特定字符串中搜索模式的任务。

re.sub() 函数本质上用于获取子字符串并将其在字符串中的出现替换为另一个子字符串。

以下代码使用 re.sub() 函数从 Python 中的字符串中删除换行符。

#import the regex library
import re

list1 = ["Starbucks\n", "has the \nbest", "coffee\n\n "]
  
rez = []
for sub in list1:
    rez.append(sub.replace("\n", ""))
          
print("New List : " + str(rez))

输出:

New List : ['Starbucks', 'has the best', 'coffee ']

以上是python如何去除字符串最后的换行符‘\n’的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:亿速云。如有侵权,请联系admin@php.cn删除
在Python阵列上可以执行哪些常见操作?在Python阵列上可以执行哪些常见操作?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

在哪些类型的应用程序中,Numpy数组常用?在哪些类型的应用程序中,Numpy数组常用?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

您什么时候选择在Python中的列表上使用数组?您什么时候选择在Python中的列表上使用数组?Apr 26, 2025 am 12:12 AM

useanArray.ArarayoveralistinpythonwhendeAlingwithHomeSdata,performance-Caliticalcode,orinterFacingWithCcccode.1)同质性data:arrayssavememorywithtypedelements.2)绩效code-performance-clitionalcode-clitadialcode-critical-clitical-clitical-clitical-clitaine code:araysofferferbetterperperperformenterperformanceformanceformancefornalumericalicalialical.3)

所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?Apr 26, 2025 am 12:05 AM

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactssperformance.2)listssdonotguaranteeconeeconeconstanttanttanttanttanttanttanttanttimecomplecomecomecomplecomecomecomecomecomecomplecomectaccesslikearrikearraysodo。

您如何在python列表中访问元素?您如何在python列表中访问元素?Apr 26, 2025 am 12:03 AM

toAccesselementsInapythonlist,useIndIndexing,负索引,切片,口头化。1)indexingStartSat0.2)否定indexingAccessesessessessesfomtheend.3)slicingextractsportions.4)iterationerationUsistorationUsisturessoreTionsforloopsoreNumeratorseforeporloopsorenumerate.alwaysCheckListListListListlentePtotoVoidToavoIndexIndexIndexIndexIndexIndExerror。

Python的科学计算中如何使用阵列?Python的科学计算中如何使用阵列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何处理同一系统上的不同Python版本?您如何处理同一系统上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通过使用pyenv、venv和Anaconda来管理不同的Python版本。1)使用pyenv管理多个Python版本:安装pyenv,设置全局和本地版本。2)使用venv创建虚拟环境以隔离项目依赖。3)使用Anaconda管理数据科学项目中的Python版本。4)保留系统Python用于系统级任务。通过这些工具和策略,你可以有效地管理不同版本的Python,确保项目顺利运行。

与标准Python阵列相比,使用Numpy数组的一些优点是什么?与标准Python阵列相比,使用Numpy数组的一些优点是什么?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基于基于duetoc的iMplation,2)2)他们的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函数函数函数函数构成和稳定性构成和稳定性的操作,制造

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具