We want to extract the day, numbers and year from a string like this
date_ = "25/12/16"
We can use the re module (regular expression)
import re
then we could use the match method, using this variable to store the result
stored = re.match("()()()",date_)
we have to put something in the () and is \d that is for digits, i.e.: numbers and we will use \d{2} to say that we want a double digit number... like 01 09 10 31 as usually we write days. Same thing for the months, while the years could be in 2 or 4 digits {2,4}.
stored = re.match("(\d{2})/(d{2})/(d{2,4})",date_)
Among the () there is the "/" sign that is the separator between the values in the string.
Now if we want the result we do:
>>> print(stored.group(1,2,3)
('25', '12', '16')
There is another way to have a similar result?
Yes, but is less sophisticated, to say so.
>>> testo.split("/")
['25', '12', '16']
The code is right after this text you're reading now:
date_ = "25/12/16"
We can use the re module (regular expression)
import re
then we could use the match method, using this variable to store the result
stored = re.match("()()()",date_)
we have to put something in the () and is \d that is for digits, i.e.: numbers and we will use \d{2} to say that we want a double digit number... like 01 09 10 31 as usually we write days. Same thing for the months, while the years could be in 2 or 4 digits {2,4}.
stored = re.match("(\d{2})/(d{2})/(d{2,4})",date_)
Among the () there is the "/" sign that is the separator between the values in the string.
Now if we want the result we do:
>>> print(stored.group(1,2,3)
('25', '12', '16')
There is another way to have a similar result?
Yes, but is less sophisticated, to say so.
>>> testo.split("/")
['25', '12', '16']
The code is right after this text you're reading now:
import re
testo = "25/12/16"
stored = re.match("(\d{2})/(\d{2})/(\d{2,4})",testo)
print(stored.group(1,2,3))
print(testo.split("/"))
Comments
Post a Comment