New line and tab characters in python on mac

我是研究僧i 提交于 2019-12-13 05:36:38

问题


I am printing a string to the python shell on a mac os 10.7.3.

The string contains new line characters, \n\r, and tabs, \t.

I'm not 100% sure what new line characters are used on each platform, however i've tried every combination (\n, \n\r, \r) and the newline characters are printed on the shell:

 'hello\n\r\tworld'

I don't know what i'm doing wrong, any help is appreciated.

Thanks


回答1:


What look to you like newlines and carriage returns are actually two characters each -- a back slash plus a normal character.

Fix this by using your_string.decode('string_escape'):

>>> s = 'hello\\n\\r\\tworld'   # or s = r'hello\n\r\tworld'
>>> print s
hello\n\r\tworld
>>> print repr(s)
'hello\\n\\r\\tworld'
>>> print s.decode('string_escape')
hello
        world


来源:https://stackoverflow.com/questions/10420337/new-line-and-tab-characters-in-python-on-mac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!