简体   繁体   English

Python字符串文字-字符串中包括单引号和双引号

[英]Python string literals - including single quote as well as double quotes in string

I want to join this series of strings: 我想加入这一系列的字符串:

my_str='"hello!"' + " it's" + ' there'

Want the result to be: 希望结果是:

my_str
Out[65]: '"hello!" it's there'

But I get: 但是我得到:

my_str
Out[65]: '"hello!" it\'s there'

I have tried a few iterations but none seem to work. 我尝试了几次迭代,但似乎都没有效果。

The result is correct. 结果是正确的。 Single quotes have to be escaped in single quoted strings. 单引号必须在单引号字符串中转义。 The same for double quotes. 双引号相同。

If you try print the result, you'll see that it's as you expected. 如果您尝试print结果,您会发现它与预期的一样。

>>> print(my_str)
"hello!" it's there

if you use print command you will see as you want... 如果使用print命令,您将看到所需的...

>>> my_str='"hello!"' + " it's" + ' there'
>>> my_str
'"hello!" it\'s there' #Count printed characters. You will count 22
>>> print my_str
"hello!" it's there
#Now count characters. 19
>>> len(my_str)
19
#see count of characters.

Using only "my_str" without any command/function shows only memory. 仅使用“ my_str”而不使用任何命令/功能仅显示内存。 but if you want process with string u will get "'" without "\\"... 但是,如果要使用字符串u进行处理,则将得到“'”而不包含“ \\” ...

print my_str will print your string as print my_str将您的字符串打印为

'"hello!" it's there'

You can also do that stuff in another way using my_str.decode('ascii') 您还可以使用my_str.decode('ascii')以另一种方式执行该操作

new_str = my_str.decode('ascii')
print new_str

It will print the string as: 它将字符串打印为:

"hello!" it's there

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

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