>>> 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?'
>>>
如何用
raw_input
输入换行符?但是,一旦你有一个字符串,其中有一些字符你想摆脱,只要replace
他们。在上面的例子中,我替换了所有空格。字符串
'\n'
表示换行符。而\r
表示回车(如果您在windows上,您可能会得到这些,第二个replace
将为您处理它们!)。基本上:
另外,请注意,调用变量
string
是一个坏主意,因为这会隐藏模块string
。另一个名字我会避免,但有时会喜欢使用:file
。出于同样的原因。您可以尝试使用字符串替换:
可以在不使用分隔符arg的情况下拆分字符串,这将把连续的空白视为单个分隔符(包括换行符和制表符)。然后使用空格连接:
https://docs.python.org/2/library/stdtypes.html#str.split
相关问题 更多 >
编程相关推荐