首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从我的数组中的字符串中摆脱\n

如何从我的数组中的字符串中摆脱\n
EN

Stack Overflow用户
提问于 2018-10-24 08:45:45
回答 2查看 44关注 0票数 0

代码如下所示:

代码语言:javascript
复制
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)

最终结果如下所示:

代码语言:javascript
复制
['the\n', 'be\n', 'and\n', 'of\n', 'a\n', 'in\n', 'to\n', 'have\n', 'it\n'.......

如何从元素的末尾去掉\n。我试过rsplit,但我不明白为什么它不起作用。我对编程真的很陌生!

EN

回答 2

Stack Overflow用户

发布于 2018-10-24 08:49:24

大家好,欢迎来到StackOverflow!

尝试lexicon.replace() ok,这样对于每个this线程,看起来都需要使用由'\‘或r()表示的“原始”字符。

所以它应该看起来像这样。

代码语言:javascript
复制
lexicon.replace('\\n', "")

让我知道这是否有效!

票数 0
EN

Stack Overflow用户

发布于 2018-10-24 08:52:32

这应该会删除'\n':

代码语言:javascript
复制
lexicon = [i.strip('\n') for i in lexicon]
print(lexicon)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52959624

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档