我有一个类似这样的文本文件(假设 A 和 B 是人,下面的文本是他们之间的对话):
A: Hello
B: Hello
A: How are you?
B: I am good. Thanks and you?
Run Code Online (Sandbox Code Playgroud)
我将此对话添加到返回以下结果的列表中:
[['A', 'Hello\n'], ['A', 'How are you?\n'], ['B', 'Hello\n'], ['B', 'I am good. Thanks and you?\n']]
Run Code Online (Sandbox Code Playgroud)
我循环使用这些命令:
new_sentence = line.split(': ', 1)[1]
attendees_and_sentences[index].append(person)
attendees_and_sentences[index].append(new_sentence)
print(attendees_and_sentences) # with this command I get the above result
print(attendees_and_sentences[0][1]) # if I run this one, then I don't get "\n" in the sentence.
Run Code Online (Sandbox Code Playgroud)
问题是我的结果屏幕上的那些“\n”字符。我怎样才能摆脱它们?
谢谢。
您可以使用Python的rstrip函数。
例如:
>>> 'my string\n'.rstrip()
'my string'
Run Code Online (Sandbox Code Playgroud)
如果您想在保留其他空格的同时修剪尾随换行符,则可以指定要删除的字符,如下所示:
>>> 'my string \n'.rstrip()
'my string '
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22140 次 |
| 最近记录: |