删除长文本字符串中的所有换行符

基本上,我要求用户在控制台中输入一个文本字符串,但是这个字符串非常长,并且包含许多换行符。如何获取用户的字符串并删除所有换行符,使其成为一行文本。我获取字符串的方法非常简单。

string = raw_input("Please enter string: ")

有没有一种不同的方式,我应该从用户抓取字符串?我在 Mac 上运行 Python 2.7.4。

附注: 显然我是个菜鸟,所以即使一个解决方案不是最有效的,使用最简单语法的方案也会受到欢迎。

504385 次浏览

您可以尝试使用字符串替换:

string = string.replace('\r', '').replace('\n', '')

如何使用 raw_input输入换行符?但是,一旦你有一个字符串,其中有一些字符你想摆脱,只是 replace他们。

>>> mystr = raw_input('please enter string: ')
please enter string: hello world, how do i enter line breaks?
>>> # pressing enter didn't work...
...
>>> mystr
'hello world, how do i enter line breaks?'
>>> mystr.replace(' ', '')
'helloworld,howdoienterlinebreaks?'
>>>

在上面的例子中,我替换了所有的空格。字符串 '\n'表示换行符。而 \r表示回车(如果你在窗口上,你可能会得到这些,第二个 replace将为你处理它们!).

基本上:

# you probably want to use a space ' ' to replace `\n`
mystring = mystring.replace('\n', ' ').replace('\r', '')

另请注意,调用变量 string是一个坏主意,因为这会影响模块 string。另一个我会避免但有时会喜欢使用的名字: file。出于同样的原因。

根据 Xbello评论更新:

string = my_string.rstrip('\r\n')

阅读更多 给你

您可以不使用分隔符参数分割字符串,该参数将连续的空格视为单个分隔符(包括换行符和制表符)。然后使用一个空格加入:

In : " ".join("\n\nsome    text \r\n with multiple whitespace".split())
Out: 'some text with multiple whitespace'

Https://docs.python.org/2/library/stdtypes.html#str.split

考虑因素的方法

  • 在字符串的开头/结尾处增加白字符
  • 在每行的开头/结尾增加白色字符
  • 各种结尾字符

它需要这样一个多行字符串,这可能是混乱的,例如。

test_str = '\nhej ho \n aaa\r\n   a\n '

产生漂亮的一行字符串

>>> ' '.join([line.strip() for line in test_str.strip().splitlines()])
'hej ho aaa a'

更新: 修复产生多余空格的多个新行字符:

' '.join([line.strip() for line in test_str.strip().splitlines() if line.strip()])

这也适用于以下情况 test_str = '\nhej ho \n aaa\r\n\n\n\n\n a\n '

另一个选择是 regex:

>>> import re
>>> re.sub("\n|\r", "", "Foo\n\rbar\n\rbaz\n\r")
'Foobarbaz'

rstrip()的问题在于,它并不是在所有情况下都能正常工作(正如我自己看到的那样)。相反,你可以使用

text = text.replace("\n"," ")

这将删除带有空格的所有新行 '\n'

如果有人决定使用 replace,您应该尝试使用 r'\n'而不是 '\n'

mystring = mystring.replace(r'\n', ' ').replace(r'\r', '')

用 Python 编写的 规范的回答应该是:

s = ''.join(s.splitlines())

它将字符串分成几行(让 Python 根据自己的最佳实践来完成)。然后合并它。这里有两种可能性:

  • 用空格(' '.join())替换换行符
  • 或者没有空格(''.join())

正则表达式是实现这一点的最快方法

s='''some kind   of
string with a bunch\r of


  

extra spaces in   it'''


re.sub(r'\s(?=\s)','',re.sub(r'\s',' ',s))

结果:

'some kind of string with a bunch of extra spaces in it'