0

Good evening. Today, I was writing a piece of code in Python. I have a string that is called date. It holds the following data:

date='05/04/2014'

So. I want to split this string into several substrings, each holding the day, month or year. These substrings will be called day, month and year, with the respective number in each string. How could I do this?

Also, I would like this method to work for any other date strings, such as:

02/07/2012
5
  • 3
    d,m,y = date.split("/") Commented Mar 2, 2017 at 18:18
  • Possible duplicate of How to split a string into two integers in Python? Commented Mar 2, 2017 at 18:19
  • @Jean-FrançoisFabre excellent! You should post that as an answer so I could accept it. Commented Mar 2, 2017 at 18:19
  • 1
    Willem already did. You can accept his. Commented Mar 2, 2017 at 18:20
  • @Jean-FrançoisFabre oh I didn't notice k Commented Mar 2, 2017 at 18:21

1 Answer 1

2

Simply use:

day,month,year = date.split('/')

Here you .split(..) the string on the slash (/) and you use sequence unpacking to store the first, second and third group in day, month and year respectively. Here date is the string that contains the date ('05/04/2014') and '/' is the split pattern.

>>> day,month,year = date.split('/')
>>> day
'05'
>>> month
'04'
>>> year
'2014'

Note that day, month and year are still strings (not integers).

Sign up to request clarification or add additional context in comments.

3 Comments

I assume that "/" is my string of the date?
@pagie_: no date is the string of your date in date.split(..). '/' is the splitter.
oh i see. thanks ill accept when stackoverflow lets me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.