search
HomeBackend DevelopmentPython TutorialHow to remove the newline character '\n' at the end of a string in python

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 ']

The above is the detailed content of How to remove the newline character '\n' at the end of a string in python. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How are arrays used in scientific computing with Python?How are arrays used in scientific computing with Python?Apr 25, 2025 am 12:28 AM

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

How do you handle different Python versions on the same system?How do you handle different Python versions on the same system?Apr 25, 2025 am 12:24 AM

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

What are some advantages of using NumPy arrays over standard Python arrays?What are some advantages of using NumPy arrays over standard Python arrays?Apr 25, 2025 am 12:21 AM

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

How does the homogenous nature of arrays affect performance?How does the homogenous nature of arrays affect performance?Apr 25, 2025 am 12:13 AM

The impact of homogeneity of arrays on performance is dual: 1) Homogeneity allows the compiler to optimize memory access and improve performance; 2) but limits type diversity, which may lead to inefficiency. In short, choosing the right data structure is crucial.

What are some best practices for writing executable Python scripts?What are some best practices for writing executable Python scripts?Apr 25, 2025 am 12:11 AM

TocraftexecutablePythonscripts,followthesebestpractices:1)Addashebangline(#!/usr/bin/envpython3)tomakethescriptexecutable.2)Setpermissionswithchmod xyour_script.py.3)Organizewithacleardocstringanduseifname=="__main__":formainfunctionality.4

How do NumPy arrays differ from the arrays created using the array module?How do NumPy arrays differ from the arrays created using the array module?Apr 24, 2025 pm 03:53 PM

NumPyarraysarebetterfornumericaloperationsandmulti-dimensionaldata,whilethearraymoduleissuitableforbasic,memory-efficientarrays.1)NumPyexcelsinperformanceandfunctionalityforlargedatasetsandcomplexoperations.2)Thearraymoduleismorememory-efficientandfa

How does the use of NumPy arrays compare to using the array module arrays in Python?How does the use of NumPy arrays compare to using the array module arrays in Python?Apr 24, 2025 pm 03:49 PM

NumPyarraysarebetterforheavynumericalcomputing,whilethearraymoduleismoresuitableformemory-constrainedprojectswithsimpledatatypes.1)NumPyarraysofferversatilityandperformanceforlargedatasetsandcomplexoperations.2)Thearraymoduleislightweightandmemory-ef

How does the ctypes module relate to arrays in Python?How does the ctypes module relate to arrays in Python?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function