【问题标题】:Converting String list to pure list in Python在 Python 中将字符串列表转换为纯列表
【发布时间】:2017-05-23 10:59:04
【问题描述】:

我有一个来自 bash 的字符串类型列表,如下所示:

inp = "["一","二","三","四","五"]"

输入来自 bash 脚本。 在我的 python 脚本中,我想以这种格式将其转换为普通的 python 列表:

["一","二","三","四","五"]

其中所有元素都是字符串,但整个薄表示为列表。

我试过了:list(inp) 这没用。有什么建议吗?

【问题讨论】:

标签: python bash list


【解决方案1】:

试试这个代码,

import ast
inp = '["one","two","three","four","five"]'
ast.literal_eval(inp) # will prints ['one', 'two', 'three', 'four', 'five']

【讨论】:

    【解决方案2】:

    看看ast.literal_eval:

    >>> import ast
    >>> inp = '["one","two","three","four","five"]'
    >>> converted_inp = ast.literal_eval(inp)
    >>> type(converted_inp)
    <class 'list'>
    >>> print(converted_inp)
    ['one', 'two', 'three', 'four', 'five']
    

    请注意,您的原始输入字符串不是有效的 Python 字符串,因为它在 "[" 之后结束。

    >>> inp = "["one","two","three","four","five"]"
    SyntaxError: invalid syntax
    

    【讨论】:

      【解决方案3】:

      使用re.sub()str.split()函数的解决方案:

      import re
      inp = '["one","two","three","four","five"]'
      l = re.sub(r'["\]\[]', '', inp).split(',')
      
      print(l)
      

      输出:

      ['one', 'two', 'three', 'four', 'five']
      

      【讨论】:

        【解决方案4】:

        你可以像下面这样使用替换和拆分:

        >>> inp
        "['one','two','three','four','five']"
        
        >>> inp.replace('[','').replace(']','').replace('\'','').split(',')
        ['one', 'two', 'three', 'four', 'five']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-11-15
          • 1970-01-01
          • 1970-01-01
          • 2014-08-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-14
          相关资源
          最近更新 更多