【问题标题】:In Python interpreter, return without " ' "在 Python 解释器中,返回不带“'”
【发布时间】:2010-12-01 17:51:58
【问题描述】:

在 Python 中,如何返回如下变量:

function(x):
   return x

没有'x' (') 在x 周围?

【问题讨论】:

    标签: python interpreter read-eval-print-loop


    【解决方案1】:

    在 Python 交互提示中,如果你返回一个字符串,它会被显示并用引号括起来,主要是为了让你知道它是一个字符串。

    如果你只是打印字符串,它不会用引号显示(除非字符串引号)。

    >>> 1 # just a number, so no quotes
    1
    >>> "hi" # just a string, displayed with quotes
    'hi'
    >>> print("hi") # being *printed* to the screen, so do not show quotes
    hi
    >>> "'hello'" # string with embedded single quotes
    "'hello'"
    >>> print("'hello'") # *printing* a string with embedded single quotes
    'hello'
    

    如果您确实确实需要删除前导/尾随引号,请使用字符串的.strip方法删除单引号和/或双引号:

    >>> print("""'"hello"'""")
    '"hello"'
    >>> print("""'"hello"'""".strip('"\''))
    hello
    

    【讨论】:

      【解决方案2】:

      这是删除字符串中所有单引号的一种方法。

      def remove(x):
          return x.replace("'", "")
      

      这是另一个删除第一个和最后一个字符的替代方法。

      def remove2(x):
          return x[1:-1]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-16
        • 1970-01-01
        • 2012-03-08
        • 1970-01-01
        • 2020-06-22
        • 2018-11-07
        相关资源
        最近更新 更多