从一长串文本中删除所有换行符
基本上,我要求用户input一串文本到控制台,但string很长,包括许多换行符。 我将如何获取用户的string,并删除所有换行符,使其成为一行文本。 我的获取string的方法非常简单。
string = raw_input("Please enter string: ") 有没有不同的方式,我应该从用户抓取string? 我在Mac上运行Python 2.7.4。
PS很明显,我是一个noob,所以即使一个解决scheme不是最有效的,使用最简单的语法,将不胜感激。
 如何用raw_inputinput换行符? 但是,一旦你有一个string中的一些字符,你想摆脱,只是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?' >>> 
 在上面的例子中,我replace了所有的空格。 string'\n'代表换行符。 而\r代表回车(如果你在窗户上,你可能会得到这些,第二次replace会为你处理!)。 
基本上:
 # you probably want to use a space ' ' to replace `\n` mystring = mystring.replace('\n', ' ').replace('\r', '') 
 还要注意,调用variablesstring是个坏主意,因为这会影响模块string 。 另一个名字,我会避免,但有时会喜欢使用: file 。 为了同样的原因。 
你可以尝试使用stringreplace:
 string = string.replace('\r', '').replace('\n', '') 
 更新根据Xbello评论: 
 string = my_string.rstrip('\r\n') 
在这里阅读更多
您可以拆分string,没有分隔符arg,将连续空格视为单个分隔符(包括换行符和制表符)。 然后join使用空间:
 In : " ".join("\n\nsome text \r\n with multiple whitespace".split()) Out: 'some text with multiple whitespace' 
考虑的方法
- 在string的开头/结尾附加白色字符
- 在每一行的开始/结尾添加白色字符
- 各种结束字符
它需要这样一个多线串可能是混乱的,例如
 test_str = '\nhej ho \n aaa\r\na\n ' 
并产生很好的单行string
 >>> ' '.join([line.strip() for line in test_str.strip().splitlines()]) 'hej ho aaa a'