Search code examples
pythonmysqlnullnonetype

Python change format for only certain items in list


I have a list like this:

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

And I used this code to get it into this format (because I'm going to insert it into a mysql table):

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

Output:

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

Which is almost exactly what I want, except I do not want the NULL in quotes (if it goes in as quotes then mysql interprets that as 0, but I need it to be inserted as null). I also have many lists that I need to make sure the NULL is not in quotes but everything else is. How can I do this?

I also tried using python's None instead of 'NULL' but when I need to change the format from a list to comma separated values, python doesn't like the NoneType.


Solution

  • Maybe this also work:

    >>> 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'