Retain the "\n"
>>> t = "first%s\n"
>>> t = t %("second")
>>> print t
firstsecond
开发者_StackOverflow中文版
Is there anyway I could retain the "\n" at the end and get "firstsecond\n" as the output?
You need to escape the slash
>>> t = "first%s\\n"
>>> t = t %("second")
>>> print t
or use raw strings:
>>> t = r"first%s\n"
>>> t = t %("second")
>>> print t
print "firstsecond\n"
displays "firstsecond" and the cursor is pushed to the next new line. So you don't see any backslash followed by n. Because the display of strings implies that the special characters such as \n are interpreted.
repr() prevents the interpretation so print repr("firstsecond\n")
displays firstsecond\n
Then, what do you want ? :
t being "firstsecond\n" and to display repr(t) to verify that there is the character \n in it ?
or t being "firstsecond\\n" in order that
print t
will display firstsecond\n ?
See:
t = "first%s\n"
print repr(t),len(t)
t = t %("second")
print repr(t),len(t)
print '-------------------'
t = "first%s\\n" # the same as r"first%s\n"
print repr(t),len(t)
t = t %("second")
print repr(t),len(t)
result
'first%s\n' 8
'firstsecond\n' 12
-------------------
'first%s\\n' 9
'firstsecond\\n' 13
But don't make misinterpretation: when there is a display like that:
'first%s\\n'
,
the two backslashes \\ mean a value of ONE backslash. The two \\ appear only on the screen to express the value of a backslash in an escaped manner. Otherwise, it couldn't be possible to differentiate the two characters consisting of \ followed by n and the unique character \n
Depending on what do you need exactly, you may also check repr().
>>> s = "firstsecond\n"
>>> print repr(s)
'firstsecond\n'
精彩评论