Finding the day from a given date

  • Context: Python 
  • Thread starter Thread starter Taylor_1989
  • Start date Start date
  • Tags Tags
    Word problem
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
31 replies · 5K views
Mark44 said:
Does the notation a[0:4] represent the characters in the string from index 0 through index 4? If so, that's five characters. And similarly in a[6:8], which I believe would be the three characters at indexes 6, 7, and 8.

I believe this is what you want:
year = (int(a[0:3]))
month = (int((a[4:5])))
day = (int(a[6:7]))
The index slice is being used to read the year and month and day from the string as u mentioned. I am now slightly confused to how my slicing produces the desired result for the year as you are right the index [0:3] should read the first four characters of the string '2018' however when I run the index from [0:3] it printed:

Python:
# Input date from the user/ for now just string in put
a = '20180101'# Define variable for the year, month and day and converting integer values
year = (int(a[0:3]))
print(year)
print('')
y = (int(a[0:4]))
print(y)

[CODE title="Output"]201

2018[/CODE]

So now my question is why is it reading in 5 characters for 2018 and not 4?
 
Last edited by a moderator:
Physics news on Phys.org
Taylor_1989 said:
The index slice is being used to read the year and month and day from the string as u mentioned. I am now slightly confused to how my slicing produces the desired result for the year as you are right the index [0:3] should read the first four characters of the string '2018' however when I run the index from [0:3] it printed:
That was my mistake in not remembering how Python does things with array slices. Your expression a[0:4] evaluates to the string from a[0] up to but not including a[4].
The portion of the string starting at a[4] up to but not including a[6] gives you the two characters at indexes 4 and 5. And similarly for the last two characters at indexes 6 and 7.

The following runs in Python for an array a with 8 characters:
Python:
year = (int(a[0:4]))
month = (int((a[4:6])))
day = (int(a[6:8]))
 
  • Like
Likes   Reactions: Taylor_1989