简体   繁体   English

是否可以从python中的字符串列表中删除所有单引号?

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

I have 3 lists, yearlist, monthlist and daylist. 我有3个列表,年级列表,月份列表和日期列表。 I'm trying to combine all 3 and add strings between them. 我正在尝试组合所有3并在它们之间添加字符串。

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)'] 这将singledate打印为datetime(year=2009, month=01, day=15) ,但datelist为['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. 因为你的singledate是一个字符串。 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, 如果您正在寻找datetime ,您不想使用字符串,尝试这样的事情,

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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