简体   繁体   中英

Is it possible to remove all single quotes from a list of strings in python?

I have 3 lists, yearlist, monthlist and daylist. I'm trying to combine all 3 and add strings between them.

for i in range(0,j):
    singledate = 'datetime(year=' + yearlist[i] + ', month=' + monthlist[i] + ', day=' + daylist[i] + ')'
    datelist.append(singledate)
print singledate
print datelist

This prints singledate as datetime(year=2009, month=01, day=15) , but datelist as ['datetime(year=2009, month=02, day=14)', 'datetime(year=2009, month=01, day=15)']

Is it possible to remove all " ' " in datelist? Thanks

This is expected here. As your singledate is a string. and datelist is list. so when you print the same it will get printed the format as shown above.

You can join the list into a string and get the output as you asked like this. I am doing a join on your datelist and print the same.

for i in range(0,j):
    singledate = 'datetime(year=' + yearlist[i] + ', month=' + monthlist[i] + ', day=' + daylist[i] + ')'
    datelist.append(singledate)
print singledate
print " ".join(datelist)

If you are looking for datetime , You don't want to use string, Try something like this,

In [12]: import datetime
In [13]: datelist = [datetime.datetime(yearlist[i],monthlist[i],daylist[i]) for i in range(0,j)]

Result

[datetime.datetime(2009, 1, 14, 0, 0), datetime.datetime(2009, 2, 15, 0, 0)]

The quotes are displayed because you are directly printing a list containing strings. This is the normal and desired behavior.

>>> alist = ['a', 'b', 'c']
>>> print(alist)
['a', 'b', 'c']

If you want to print the same content without quotes, you have to format it by yourself:

>>> print('[{}]'.format(', '.join(alist)))
[a, b, c]

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