从一长串文本中删除所有换行符 [英] Remove all line breaks from a long string of text
问题描述
基本上,我要求用户在控制台中输入一串文本,但该字符串很长并且包含许多换行符.我将如何获取用户的字符串并删除所有换行符以使其成为单行文本.我获取字符串的方法很简单.
string = raw_input("请输入字符串:")
我应该从用户那里获取字符串有什么不同的方式吗?我在 Mac 上运行 Python 2.7.4.
附言显然我是个菜鸟,所以即使解决方案不是最有效的,使用最简单语法的解决方案也会受到赞赏.
如何使用 raw_input
输入换行符?但是,一旦你有一个包含一些你想要删除的字符的字符串,只需替换
它们.
在上面的例子中,我替换了所有空格.字符串 '\n'
代表换行符.而 \r
代表回车(如果你在 Windows 上,你可能会得到这些,第二个 replace
会为你处理它们!).
基本上:
# 你可能想用空格 ' ' 来代替 `\n`mystring = mystring.replace('\n', ' ').replace('\r', '')
另请注意,调用变量 string
是个坏主意,因为这会遮蔽模块 string
.另一个我会避免但有时会喜欢使用的名称:file
.出于同样的原因.
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.
How do you enter line breaks with raw_input
? But, once you have a string with some characters in it you want to get rid of, just replace
them.
>>> 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?'
>>>
In the example above, I replaced all spaces. The string '\n'
represents newlines. And \r
represents carriage returns (if you're on windows, you might be getting these and a second replace
will handle them for you!).
basically:
# you probably want to use a space ' ' to replace `\n`
mystring = mystring.replace('\n', ' ').replace('\r', '')
Note also, that it is a bad idea to call your variable string
, as this shadows the module string
. Another name I'd avoid but would love to use sometimes: file
. For the same reason.
这篇关于从一长串文本中删除所有换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!