Search code examples
pythonpython-2.7strptime

Why is there comma in my slice


When I did slice for my date/month/year, there's always this "()" & ",". May I know how do I get rid of it? user input = 21/12/1999 output = (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)

Solution

  • get_dateOfBirth returns a tuple, and performing slicing on a tuple gives you a tuple.

    If you want birthDate, birthMonth, and birthYear to be regular integers, instead of tuples containing one integer apiece, use indexing instead of slicing.

    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)
    

    Result:

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