Python字符串文字 - 包括单引号以及字符串中的双引号

时间:2016-08-02 07:50:57

标签: python

我想加入这一系列字符串:

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

希望结果为:

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

但我明白了:

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

我尝试了几次迭代,但似乎都没有。

3 个答案:

答案 0 :(得分:3)

结果是正确的。单引号必须在单引号字符串中转义。双引号也一样。

如果您尝试print结果,您会发现它符合您的预期。

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

答案 1 :(得分:2)

如果你使用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.

仅使用“my_str”而没有任何命令/功能仅显示内存。 但是如果你想要用字符串处理你将得到“'”而没有“\”......

答案 2 :(得分:1)

print my_str会将您的字符串打印为

'"hello!" it's there'

您也可以使用my_str.decode('ascii')

以其他方式执行此操作
new_str = my_str.decode('ascii')
print new_str

它会将字符串打印为:

"hello!" it's there

相关问题