【问题标题】:Python string literals - including single quote as well as double quotes in stringPython 字符串文字 - 包括字符串中的单引号和双引号
【发布时间】:2016-08-02 07:50:56
【问题描述】:

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

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

希望结果是:

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

但我明白了:

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

我已经尝试了几次迭代,但似乎都不起作用。

【问题讨论】:

  • 你想要得到的结果是不可能实现的。通过不转义',python 会假定这是字符串的结尾。因此,您需要使用 `` 显式转义它才能正确解析它。您实际上可以在堆栈溢出语法突出显示中很好地看到这一点
  • 试试print(my_str) 告诉我们是否真的有问题。

标签: python


【解决方案1】:

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

如果您尝试print 的结果,您会发现它与您预期的一样。

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

【讨论】:

    【解决方案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”而不使用任何命令/函数仅显示内存。 但是如果你想用字符串处理你会得到没有“\”的“'”......

    【讨论】:

      【解决方案3】:

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

      '"hello!" it's there'

      您也可以使用 my_str.decode('ascii') 以另一种方式完成这些工作

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

      它将字符串打印为:

      "hello!" it's there

      【讨论】:

        猜你喜欢
        • 2014-09-26
        • 1970-01-01
        • 1970-01-01
        • 2011-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多