【问题标题】:Python change format for only certain items in listPython仅更改列表中某些项目的格式
【发布时间】:2017-08-30 21:10:49
【问题描述】:

我有一个这样的列表:

lst = ['3:44:44', '1.', '0', '2P', 'ri', 'NULL', 'fs']

我使用这段代码将它变成了这种格式(因为我要把它插入到一个 mysql 表中):

"'{}'".format("','".join(lst))

输出:

'3:44:44','1.','0','2P','ri','NULL','fs'

这几乎正是我想要的,除了我不希望引号中的 NULL(如果它作为引号出现,那么 mysql 会将其解释为 0,但我需要将其插入为 null)。我还有许多列表,我需要确保 NULL 不在引号中,但其他所有内容都在引号中。我该怎么做?

我也尝试使用 python 的 None 而不是 'NULL',但是当我需要将格式从列表更改为逗号分隔值时,python 不喜欢 NoneType。

【问题讨论】:

  • 你可以搜索/替换引用的 NULL...
  • NULL 是否需要在字符串中的确切位置?
  • @lee-pai-long 是的,确实如此。顺序对我插入的所有内容都很重要。
  • "'{}'".format("','".join(lst)).replace("'NULL'", 'NULL')
  • 你可以试试得到这个值吗? '3:44:44','1.','0','2P','ri',NULL,'fs'

标签: python mysql null nonetype


【解决方案1】:

也许这也有效:

>>> lst = ['3:44:44', '1.', '0', '2P', 'ri', 'NULL', 'fs']
>>> print ("'{}'".format("','".join(lst)).replace("'NULL'", 'NULL'))
'3:44:44','1.','0','2P','ri',NULL,'fs'

【讨论】:

  • 不错的解决方案 ;)
  • 我们都认为相同的解决方案@sKwa
【解决方案2】:

如果您将其作为字符串插入,为什么不忽略“Null”。所以输入就像

lst = ['3:44:44', '1.', '0', '2P', 'ri', 'NULL', 'fs'].

"'{}'".format("','".join([x if x!='NULL' else '' for x in lst]))

输出应该是那么

"'3:44:44','1.','0','2P','ri','','fs'"

它应该将 '' 读取为空值或 null。

【讨论】:

    【解决方案3】:

    Pythonic 清晰的方式:

    In [41]: def quote_item(item):
        ...:     if item == "NULL":
        ...:         return item
        ...:     else:
        ...:         return "'{}'".format(item)
        ...:   
    
    In [42]: result = ",".join(quote_item(item) for item in lst)
    
    In [43]: print(result)
    '3:44:44','1.','0','2P','ri',NULL,'fs'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-18
      • 2012-11-02
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多