Search code examples
pythonmysql-connector

how do i convert a list into a string


i have tried to use the .replace or .strip method but have been unsuccessful with doing such. I am trying to print out a single stringed list separated by commas.

does anyone know a way to make it so it us printing out with no [] or single quotes ''

def get_format(header1):
    format_lookup = "SELECT ID, FormatName, HeaderRow, ColumnStatus, ColumnMobileID, ColumnVendorID, ColumnTechID, " \
                    "ColumnCallType, ColumnCallDate, ColumnCallTime, ColumnCallTo, ColumnQty, ColumnQtyLabel " \
                    "from dynamic_format WHERE HeaderRow=%s"
    
    header1 = (str(header1),)
    cursor = connection.cursor()
    cursor.execute(format_lookup, header1)
    record = cursor.fetchone()

    return record

Solution

  • I suppose I'll post my comment as an answer:

    In [1]: header1 = ['ESN', 'ORIGINAL_QUANTITY', 'INVOICE_DATE']
    
    In [2]: ", ".join(header1)
    Out[2]: 'ESN, ORIGINAL_QUANTITY, INVOICE_DATE'
    
    In [3]: print(", ".join(header1))
    ESN, ORIGINAL_QUANTITY, INVOICE_DATE
    

    The reason you're getting those errors is because header1 is a list object and .replace() is a string method.

    @sbabtizied's answer is what you'd use if header1 was a string:

    # a single string, what sbabti assumed you had
    "['ESN', 'ORIGINAL_QUANTITY', 'INVOICE_DATE']"
    
    # a list of strings, what you actually have
    ['ESN', 'ORIGINAL_QUANTITY', 'INVOICE_DATE']