为什么我的切片中有逗号

Why is there comma in my slice

当我为 date/month/year 切片时, 总是有这个 "()" & ","。 我可以知道如何摆脱它吗? 用户输入 = 21/12/1999 输出 = (1999,12,21)

def get_dateOfBirth():
    while True:
        dateOfBirth_input = raw_input("Please enter your date of birth in DD/MM/YYYY format: ")
        try:
            result = strptime(dateOfBirth_input, "%d/%m/%Y")
        except ValueError:
            print "Please Key in the valid Date Of Birth"
        else:
            return result[:3]

dateOfBirth = get_dateOfBirth()
birthDate = dateOfBirth[2:3]
birthMonth = dateOfBirth[1:2]
birthYear = dateOfBirth[:1]

print "date is" + str(birthDate)
print "month is" + str(birthMonth)
print "year is" + str(birthYear)

get_dateOfBirth returns 一个元组,对一个元组执行切片得到一个元组。

如果您希望 birthDatebirthMonthbirthYear 是常规整数,而不是每个包含一个整数的元组,请使用索引而不是切片。

dateOfBirth = get_dateOfBirth()
birthDate = dateOfBirth[2]
birthMonth = dateOfBirth[1]
birthYear = dateOfBirth[0]

#bonus style tip: add a space between 'is' and the number that follows it
print "date is " + str(birthDate)
print "month is " + str(birthMonth)
print "year is " + str(birthYear)

结果:

Please enter your date of birth in DD/MM/YYYY format: 21/12/1999
date is 21
month is 12
year is 1999

time.strptime 函数实际上 returns 一个 struct_time 对象,但如果您将其视为元组,该对象将表现得像元组。所以你可以使用切片和索引来访问它的属性,以及属性访问的标准语法,例如dateOfBirth.tm_year。使用属性访问语法比使用元组访问更清晰,并且您无需担心记住不同属性的顺序。OTOH,基于元组的方法通常会产生更短(如果更神秘)的代码。

在这个版本的程序中,我使用了 * 解包运算符(又名 "splat" 运算符)将所需字段传递给 format 函数; struct_time 对象在该上下文中的行为类似于元组。我还导入了 readline 模块,它会自动将行编辑添加到 raw_input(),如果用户出错并需要重新输入数据,这很好。但是,并非所有平台都支持 readline

我还将提示字符串从 raw_input() 调用中移出,使代码看起来更整洁,并稍微优化了 try:...except 块。

from time import strptime
import readline

def get_dateOfBirth():
    prompt = "Please enter your date of birth in DD/MM/YYYY format: "
    while True:
        dateOfBirth_input = raw_input(prompt)
        try:
            return strptime(dateOfBirth_input, "%d/%m/%Y")
        except ValueError:
            print "Please Key in the valid Date Of Birth"

dateOfBirth = get_dateOfBirth()
print "day is {2}\nmonth is {1}\nyear is {0}".format(*dateOfBirth)