【问题标题】:How to remove the quotes around the value in the string representation of a dict?如何删除字典字符串表示中值周围的引号?
【发布时间】:2020-06-10 04:47:30
【问题描述】:

如何不打印字符串周围的引号?我知道这是一个字符串,因此 Python 正在添加引号。

提供更多上下文:

def a(content):
    return {'row_contents': content}

print(a("Hello"))

这给出的输出为:

{'row_contents': 'Hello'}

我想在返回时删除 Hello 周围的引号(如下所示)

{'row_contents': Hello}

有没有简单的方法来实现这一点?

【问题讨论】:

标签: python dictionary repr


【解决方案1】:

你可以使用f string

def a(content):
    return f"{{'row_contents': {content}}}"


print(a("Hello"))

或者只是这个:

def a(content):
    return "{'row_contents':"+content+"}"

输出:

{'row_contents': Hello}

【讨论】:

    【解决方案2】:

    我仍然认为这个问题很有可能是XY problem

    但是,就目前的问题而言:如果您不想修改 print,则只需修改函数 a 的返回值即可。你上面的评论说:

    我想返回一个dict

    这听起来像是简单地返回 {'row_contents': content} 的修改字符串表示并不是您真正想要的。然而,dict.__repr__ 本身是只读的,所以我想最接近的解决方案是返回自定义 dict 子类的实例:

    class CustomDict(dict):
        def __repr__(self):
            return "{" + ", ".join([repr(k) + ": " + str(v) for k, v in self.items()]) + "}"
    
    def a(content):
        return CustomDict({'row_contents': content})
    
    print(a("Hello"))
    print(isinstance(a("Hello"), dict))
    

    哪些打印:

    {'row_contents': Hello}
    True
    

    您可能需要改进CustomDict.__repr__,具体取决于提供所需输出所需的修改。您还可以修改原始字符串表示 super().__repr__()

    【讨论】:

      【解决方案3】:

      您可以简单地获取字典的字符串表示并删除单引号。

      def a(content):
          return {'row_contents': content}
      
      def print_dict_without_quotes(d):
          print(str(d).replace("'", "").replace('"', ''))
      
      print_dict_without_quotes(a("Hello"))
      

      输出:

      {row_contents: Hello}
      

      【讨论】:

      • 然而,这也会从键中删除引号。
      猜你喜欢
      • 2018-10-29
      • 1970-01-01
      • 2020-05-16
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      • 2021-08-11
      • 1970-01-01
      • 2016-07-23
      相关资源
      最近更新 更多