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