python: how can I make this code with regular expression?

1540 views python
4

If I input "1995y 05m 05d", then I want to make a program that prints "950505"

more example: "1949y 05m 23d" --> "490523"

import re
Birthday = str(input("insert your birth<(ex) xxxxy **m 00d> : "))
p= re.sub('[ymd ]','',Birthday)
print(p) #result is "xxxx**00"

here is my code. How do I fix it? any solutions?

answered question

Any reason to use a regex and not datetime.strptime which'll also end up validating you've got a valid date and not just a pattern that looks like it could be one etc... Then format that to %y%m%d ? (but a quick fix is to just ignore the first two characters...)

As every person older than 18 years should be able to tell you: don't process or store dates with a two digit year.

@KlausD. but it saves a whole two bytes of storage - what could possibly go wrong? :p

Also... what's supposed to happen if someone just enters "this doesn't match the format asked for" or "92834927349827492387492837237"? Or... almost the right format but wrong order... eg: "23d 1949y 05m" ?

2 Answers

9

Your existing code prints the full year, where you want only two digits. Just skip the first two digits on print.

print(p[2:])

That will print p starting from position 2 (the third character, since lists are counted from 0), with no end to the range, so it prints the entire string except the first two characters (19 in your sample).

posted this
7

>>> import re
>>> a = re.findall("\d+","1995y 05m 05d")
>>> a[0] = a[0][2:]
>>> output = ""
>>> for item in a:
    output += item

>>> int(output)
950505
>>> 

posted this

Have an answer?

JD

Please login first before posting an answer.