How to receive more than one user command at once?

Asked

Viewed 49 times

0

For example:

nasc= input('INFORME SUA DATA DE NASCIMENTO: ')
RESPOSTA= 15112002

How to separate this into DAY/MONTH/YEAR ?

2 answers

1


How about:

from datetime import datetime

nasc = input("Informe sua data de nascimento: ")

try:
    obj = datetime.strptime( nasc, '%d%m%Y')
except ValueError:
    obj = None

if obj:
    print("Data Completa: %s" % (obj.strftime('%d/%m/%Y')))
    print("Dia: %s" % (obj.strftime('%d')))
    print("Mes: %s" % (obj.strftime('%m')))
    print("Ano: %s" % (obj.strftime('%Y')))
else:
    print("Data de nascimento invalida!")

Test #1:

Informe sua data de nascimento: 15112002
Data Completa: 15/11/2002
Dia: 15
Mes: 11
Ano: 2002

Test #2:

Informe sua data de nascimento: 12345678
Data de nascimento invalida!

Test #3:

Informe sua data de nascimento: 29021017
Data de nascimento invalida!

1

The more forms simple to do this are the following:

nasc is a string, strings are lists of characters. So you can split it into day, month and year.

nasc= input('INFORME SUA DATA DE NASCIMENTO: ')
dia = nasc[0:2]
mes = nasc[2:4]
ano = nasc[4:8]

Or you can use a method that you have in the own strings that is split() that returns a string list, then your user needs to type with some separating character, example: dd/mm/yyyy

>>> nasc = "20/05/1997"
>>> nasc.split('/')
['20', '05', '1997']

Browser other questions tagged

You are not signed in. Login or sign up in order to post.