连接RHCP的名称、乐器和生日

2024-10-04 11:28:28 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我正在努力实现我的标题所暗示的。我把他们的名字和乐器储存在一个列表里。我试图将他们的生日更改为字符串,以便将其与其他两个列表连接起来

Members = ["Flea", "John Frusciante", "Jack Irons", "Anthony Kiedis"]
Instruments = ["Bassist", "Guitarist", "Drummer", "Musician"]
Birthdates = str([10/16/1962, 3/5/1970, 7/18/1962, 11/1/1962])

New_list = [a + " is the " + b + " and they were born on " + c for a, b, c in zip(Members, Instruments, Birthdates)]
print "\n".join(New_list)

我的结果有点混乱,因为我没有收到任何错误。我希望这些日期可以打印出来,因为它们被记录在生日列表中

Flea is the Bassist and they were born on [
John Frusciante is the Guitarist and they were born on 0
Jack Irons is the Drummer and they were born on ,
Anthony Kiedis is the Musician and they were born on  

我知道从那时到现在,我缺少了一些步骤,但我的目标如下:

Flea is the Bassist and they were born on 16 October, 1962.

Tags: andthe列表isonjohnjackmembers
2条回答

您不能只输入像10/16/1962这样的内容作为裸文本。这是一个数学表达式。当Python看到这一点时,它会立即计算表达式的值,这就是列表中的内容:

>>> 10/16/1962
0.00031855249745158003

如果需要日期,则必须使用date对象:

>>> from datetime import date
>>> date(1962, 10, 16)
datetime.date(1962, 10, 16)
>>> str(date(1962, 10, 16))
'1962-10-16'

如果要将其格式化为16 October, 1962,则必须使用strftime()

>>> date(1962, 10, 16).strftime('%-m %B, %Y')
'10 October, 1962'

我认为只有当datetimestring时,才需要删除str

Birthdates = ['10/16/1962', '3/5/1970', '7/18/1962', '11/1/1962']

然后将字符串转换为datetime并更改输出格式:

from datetime import datetime

New_list = ["{} is the {} and they were born on {:%d, %B %Y}".format(a,b,datetime.strptime(c, '%m/%d/%Y')) for a, b, c in zip(Members, Instruments, Birthdates)]
print ("\n".join(New_list))
Flea is the Bassist and they were born on 16, October 1962
John Frusciante is the Guitarist and they were born on 05, March 1970
Jack Irons is the Drummer and they were born on 18, July 1962
Anthony Kiedis is the Musician and they were born on 01, November 1962

相关问题 更多 >