【问题标题】:Easy Way To Convert A List To A String, Still Formatted As A List将列表转换为字符串的简单方法,仍然格式化为列表
【发布时间】:2016-08-12 19:50:14
【问题描述】:

这应该很简单,但我找不到简单的解决方案。坦率地说,这应该是一个班轮。

在 Python 3 中,如何转换列表,例如

['hello','world']

到一个格式完全相同的字符串,比如

"['hello','world']"

我不想把它分成两个词。

// This is bad.
"hello world"

我想保留传统的列表格式。我最初认为您可以将列表绑定为像 (str)list_name 这样的字符串,但显然不是。没有一个简单的函数吗?

编辑:

感谢 AChampion,我发现这是一个简单的语法错误。我试图将列表绑定到这样的字符串:

//this is bad
(str)list_name

我应该这样写的时候

//this is good
str(list_name)

这正是我想要的。感谢您的帮助,很抱歉我不得不在这里提出这样一个初学者的问题。还在习惯 Python。

【问题讨论】:

    标签: python string list type-conversion


    【解决方案1】:

    列表str()repr() 都是您所要求的,假设它是一个简单字符串的列表。
    如果您有更复杂的结构并希望转换(序列化)为字符串形式并返回到对象形式,您可能需要查看json 模块:

    >>> import json
    >>> json.dumps(['hello','world'])
    '["hello", "world"]'
    

    【讨论】:

      【解决方案2】:

      简单地说:

      lst = ['hello', 'world']
      new_str = str(lst)
      print(new_str) # prints out ["hello", "world"]
      

      除非您明确告诉它,否则 Python 不会只将字符串转换为字符串格式。像这样:

      lst = ['hello', 'world']
      str1 = str(''.join(lst))
      print(str1)# prints 'helloworld'
      

      或者如果你想要一个函数:

      def listToString(lst):
          new_lst = str(lst)
          return new_lst
      

      虽然这个函数真的更像是一个包装器。我只是使用 python bulitin str() 直接转换列表,而不是尝试将其放入包装函数中。

      【讨论】:

        【解决方案3】:

        简短的回答是:你不能完全按照你的要求去做。

        您无法获取您在 Python 中键入的任何列表并获得具有完全相同原始格式的字符串。 Python 对列表中的间距非常宽松,因此您可以这样构造列表:

        1. ['hello', 'world']
        2. ['hello','world']
        3. [ 'hello', 'world' ]
        4. [ 'hello', 'world' ]

        当 Python 将这些列表创建为列表时,它不会保留有关您如何编写它的信息。所以,没有办法把它找回来。

        如果你只想要一个字符串列表,你应该使用json.dumps

        【讨论】:

          猜你喜欢
          • 2013-09-10
          • 1970-01-01
          • 2013-08-18
          • 1970-01-01
          • 2018-06-11
          • 1970-01-01
          • 2011-06-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多