【问题标题】:Django: convert string to arrayDjango:将字符串转换为数组
【发布时间】:2019-03-21 23:00:12
【问题描述】:

我有这个字符串变量

auxi_espec = '1, 3, 5, 7,'

我需要将其转换为数组,以便创建一个查询集,在其中使用__in 进行过滤。 (可能我认为我还需要分割最后一个逗号)。

【问题讨论】:

  • 你能解释一下使用__in的过滤器吗,你指的是django上的东西吗?

标签: python arrays django string parsing


【解决方案1】:

你需要使用split()函数:

>>> auxi_espec = '1, 3, 5, 7,'
>>> auxi_espec_lst = [x.strip() for x in auxi_espec.split(',')][:-1]
>>> auxi_espec_lst
['1', '3', '5', '7']

如果要将这些数字解析为整数:

>>> auxi_espec = '1, 3, 5, 7,'
>>> auxi_espec_lst = [int(x.strip()) for x in auxi_espec.split(',') if x]
>>> auxi_espec_lst
[1, 3, 5, 7]

【讨论】:

    【解决方案2】:

    Django 接受大量iterables 用于in 查找,因此如果您提到的字符串格式是一成不变的,那么这个拆分就足够了,就像字符串列表一样。

    ids = auxi_espec[0:-1].split(', ')  # ['1', '3', '5', '7']
    instances = MyModel.objects.filter(id__in=ids)
    

    【讨论】:

      【解决方案3】:

      使用正则表达式,它们很棒:

      >>> import re
      >>> auxi_espec = '1, 3, 5, 7,'
      >>> indices = re.findall(r'(\d+)', auxi_espec)
      >>> indices
      ['1', '3', '5', '7']
      >>> [int(i) for i in indices]
      [1, 3, 5, 7]
      

      【讨论】:

        猜你喜欢
        • 2017-11-27
        • 2011-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-08
        相关资源
        最近更新 更多