删除神秘的换行符python

时间:2013-06-13 11:47:29

标签: python

我的代码贯穿文本文件中的行,如下所示:

09824747 18 n 02 archer 0 bowman 0 003 @ 09640897 n 0000 ~ 10290474 n 0000 ~i 10718145 n 0000 | a person who is expert in the use of a bow and arrow

L = line.split()
L2 = line.split('|')
synset_offset = L[0]
lex_filenum = L[1]
ss_type = L[2]
gloss = L2[1]

他们打印这些看起来像这样

print('''<http://example.org/#'''+synset_offset+'''><http://www.monnetproject.eu/lemon#lex_filenum> "'''+lex_filenum+'''".
<http://example.org/#'''+synset_offset+'''> <http://www.monnetproject.eu/lemon#ss_type> "'''+ss_type+'''".
<http://example.org/#'''+synset_offset+'''> <http://www.monnetproject.eu/lemon#gloss> "'''+gloss+'''".''')

但由于某种原因,在'''+gloss+'''

之后发生了换行

看起来像这样

<http://example.org/#09824747> <http://www.monnetproject.eu/lemon#lex_filenum> "18".
<http://example.org/#09824747> <http://www.monnetproject.eu/lemon#ss_type> "n".
<http://example.org/#09824747> <http://www.monnetproject.eu/lemon#gloss> " a person who is expert in the use of a bow and arrow
".

我想删除该换行符,因为它不允许格式化文本

1 个答案:

答案 0 :(得分:4)

.split()没有参数或None作为第一个参数首先删除该行周围的空格,但.split('|')

在拆分之前明确删除它:

L2 = line.strip().split('|')

或之后:

gloss = L2[1].strip()

.strip()删除所有前导和尾随空格。您可以更具体,只使用`.rstrip():

从最后删除换行符
gloss = L2[1].rstrip('\n')