简体   繁体   中英

Convert list in python to string

I have a list like this:

my_list = ['Food']

What I need is to convert it to a string like this:

"["food"]"

Update:

I am trying to save in csv file but it gives me an empty string.

Code:

with open("food.csv", "x", encoding="utf-8") as file:
    wr = csv.writer(file)
    wr.writerow(["Food", "Id",])
    wr.writerow(str(my_list))
    wr.writerow('1')

Last update: Solved: I just needed to do the following:

with open("languages_books.csv", "x", encoding="utf-8") as file:
    wr = csv.writer(file)
    wr.writerow(["Food", "Id",)

    wr.writerows([ [[my_list]], ['Id'] ])

you can just use the str function

ans = str(my_list)

Last update: Solved: I just needed to do the following:

with open("languages_books.csv", "x", encoding="utf-8") as file:
    wr = csv.writer(file)
    wr.writerow(["Food", "Id",)

    wr.writerows([ [[my_list]], ['Id'] ])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM