我正在使用python,我需要一种快速的方式来删除字符串中的\ n的所有实例。只是要清楚,这是我想要的一个例子。正则表达式从字符串中删除换行符
"I went \n to the store\n"
成为
"I went to the store"
我想也许正则表达式将是最好的方式。
我正在使用python,我需要一种快速的方式来删除字符串中的\ n的所有实例。只是要清楚,这是我想要的一个例子。正则表达式从字符串中删除换行符
"I went \n to the store\n"
成为
"I went to the store"
我想也许正则表达式将是最好的方式。
使用str.replace
:
>>> "I went \n to the store\n".replace('\n', '')
'I went to the store'
对于间距相等,你可以先用拆分的str.split
字符串,然后加入回用str.join
:
>>> ' '.join("I went \n to the store\n".split())
'I went to the store'
我想正则表达式可能是矫枉过正这里。 – rlms
我实际上想要在大约6百万个字符串(我可能应该提到过)比这个例子字符串长得多。所以我建议正则表达式的速度,但它仍然可能是矫枉过正 – user1893354
字符串有多长?因为虽然我怀疑正则表达式会更快,但是如果字符串很长,您可能需要使用更快的语言或Python的快速实现。 – rlms