152

Basically, I'm asking the user to input a string of text into the console, but the string is very long and includes many line breaks. How would I take the user's string and delete all line breaks to make it a single line of text. My method for acquiring the string is very simple.

string = raw_input("Please enter string: ")

Is there a different way I should be grabbing the string from the user? I'm running Python 2.7.4 on a Mac.

P.S. Clearly I'm a noob, so even if a solution isn't the most efficient, the one that uses the most simple syntax would be appreciated.

4

9 回答 9

240

你如何输入换行符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代表回车(如果你在 Windows 上,你可能会得到这些,然后replace会为你处理它们!)。

基本上:

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

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

于 2013-05-15T13:28:30.940 回答
55

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

string = string.replace('\r', '').replace('\n', '')
于 2013-05-15T13:28:10.297 回答
37

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

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

于 2016-05-03T10:24:39.963 回答
15

根据Xbello评论更新:

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

在这里阅读更多

于 2014-09-24T09:43:10.520 回答
15

在 Python 中,规范的答案是:

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

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

  • 用空格 ( ' '.join())替换换行符
  • 或没有空格 ( ''.join())
于 2020-12-18T10:47:13.387 回答
9

另一种选择是正则表达式:

>>> import re
>>> re.sub("\n|\r", "", "Foo\n\rbar\n\rbaz\n\r")
'Foobarbaz'
于 2018-05-31T11:36:55.830 回答
4

如果有人决定使用,replace你应该试试r'\n''\n'

mystring = mystring.replace(r'\n', ' ').replace(r'\r', '')
于 2020-06-15T18:04:43.880 回答
3

一种考虑到的方法

  • 字符串开头/结尾的附加白色字符
  • 每行开头/结尾的附加白色字符
  • 各种结束行字符

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

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 '

于 2017-03-01T10:42:31.733 回答
1

rstrip 的问题在于它并非在所有情况下都有效(我自己很少见)。相反,您可以使用 - text= text.replace("\n"," ") 这将删除所有带有空格的新行 \n。

提前感谢你们的支持。

于 2019-05-07T08:52:08.147 回答