如何从数组中的字符串中删除 \n

代码如下所示:


import stddraw

import sys

import stdio

#open the lexicon file

lexicon_input_file = open(sys.argv[1])

# copy the lexicon over from file

lexicon = lexicon_input_file.readlines()

#close the lexicon file

lexicon_input_file.close()

for i in range(len(lexicon)): #4000 words

    # breaks down entire lexicon into each element incremented from 0,1,2,3,4,..

    line_of_text = lexicon[i]

    line_without_newline = line_of_text.rstrip('\n')

print(lexicon)

终端结果如下所示:


['the\n', 'be\n', 'and\n', 'of\n', 'a\n', 'in\n', 'to\n', 'have\n', 'it\n'.......

我如何从元素的末端摆脱 \n。我试过 rsplit 但不知道为什么它不起作用。我对编码真的很陌生!


一只萌萌小番薯
浏览 303回答 2
2回答

慕码人8056858

这应该删除 '\n':lexicon = [i.strip('\n') for i in lexicon] print(lexicon)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python