sudhakar
sudhakar

Reputation: 37

List of strings in python

I have a csv file which has a column of dates and I m importing that using the below code.

Problem is when i map that to a list of strings, it is printed as below.

["['05/06/2020']", "['1/6/2020']", "['5/22/2020']"]

With this I'm unable to check if the list contains my value(eg: another date) after doing necessary formatting.

I would like this to be

['05/06/2020', '1/6/2020', '5/22/2020']

with open('holidays.csv','r') as csv_file:
    csv_Reader = csv.reader(csv_file)
    next(csv_Reader)
    listDates = list(map(str,csv_Reader))

    print(listDates)

Upvotes: 0

Views: 61

Answers (4)

chepner
chepner

Reputation: 530960

If your file looks like this

05/06/2020
01/06/2020
05/22/2020

all you need is

with open('holidays.csv','r') as csv_file:
    csv_Reader = csv.reader(csv_file)
    next(csv_Reader)
    listDates = [row[0] for row in csv_Reader]

Each row will be a list of fields, even if there is only one field.

Upvotes: 0

Red
Red

Reputation: 27547

Like this:

l = ["['05/06/2020']", "['1/6/2020']", "['5/22/2020']"]
l = [s[2:-2] for s in l]
print(l)

Output:

['05/06/2020', '1/6/2020', '5/22/2020']

Upvotes: 0

Sahith Kurapati
Sahith Kurapati

Reputation: 1715

You can just simply add one extra line like so:

with open('holidays.csv','r') as csv_file:
    csv_Reader = csv.reader(csv_file)
    next(csv_Reader)
    listDates = list(map(str,csv_Reader))
    listDates = [x.split("'")[1] for x in listDates]

    print(listDates)

Hope this helps :)

Upvotes: 3

Austin
Austin

Reputation: 26039

Use ast.literal_eval in a list comprehension to evaluate individual elements and capture the first entry:

import ast

lst = ["['05/06/2020']", "['1/6/2020']", "['5/22/2020']"]

res = [ast.literal_eval(x)[0] for x in lst]
# ['05/06/2020', '1/6/2020', '5/22/2020']

Upvotes: 0

Related Questions