简体   繁体   English

Python字符串文字和转义序列

[英]Python String Literals and Escape Sequence

I have a string 我有一个弦

'"No, thanks, Mom," I said, "I don't know how long it will take."' ““不,谢谢,妈妈,”我说,“我不知道要花多长时间。”

I assign it to a variable foobar 我将其分配给变量foobar

>>> foobar = """'"No, thanks, Mom," I said, "I don't know how long it will take."'"""

But when I print I get 但是当我打印时

>>> foobar
'\'"No, thanks, Mom," I said, "I don\'t know how long it will take."\''
>>>

How can I exactly print the same value of the string as I have assigned it? 如何准确打印与分配的字符串相同的值?

To print a string, use ... print : 要打印字符串,请使用... print

>>> foobar = """'"No, thanks, Mom," I said, "I don't know how long it will take."'"""
>>> print(foobar)
'"No, thanks, Mom," I said, "I don't know how long it will take."'

If you just enter foobar , Python prints the representation of foobar. 如果仅输入foobar ,Python将打印foobar的表示形式。 The representation is designed to be valid Python code and/or useful for debugging, and is not meant to be outputted to users. 该表示被设计为有效的Python代码和/或对调试有用,并不表示要输出给用户。

>>> print foobar

foobar , by itself, calls repr on the string, which prints the string with escapes. foobar本身会对该字符串调用repr ,该字符串将使用转义符输出字符串。 print foobar calls str on the string instead. 在字符串上print foobar调用str代替。

It is printing the same value. 它正在打印相同的值。 It is only showing you the single quote escaped to differentiate it from the single quote used by the cmd line to display of the string. 它仅向您显示转义的单引号,以区别于cmd行用于显示字符串的单引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM