Slicing list and strings


#1


animals = "catdogfrog"
cat = animals [:3] # The first three characters of animals
dog = animals [] # The fourth through sixth characters
frog = animals [7:] # From the seventh character to the end

what is the middle number for this, it isn't listed on the hint.


Replace this line with your code.

https://www.codecademy.com/courses/python-beginner-en-pwmb1/1/3?curriculum_id=4f89dab3d788890003000096#


#2

Strings are 0-indexed.

what does that mean?

suppose.. x is a string.

x = "abcdefg"

at index 0 -- > 'a'
at index 1 -- > 'b'
at index 2 -- > 'c'
at index 3 -- > 'd'
at index 4 -- > 'e'
at index 5 -- > 'f'
at index 6 -- > 'g'

when we slice a string like this..

x[2:4] It will start slicing from index 2 to 3 excluding 4

so x[2:4] will be "cd"
also x[:3] -- >It means that slicing will start from index 0 and go including 2 - > 'abc'
also
x[3:] -- >It means that slicing will start from index 3 and ends including last index element - > 'defg'

I hope it helps.


#3

https://www.codecademy.com/courses/python-beginner-en-pwmb1/1/3?curriculum_id=4f89dab3d788890003000096

[3:7] and it says it spells dogf
[3:6] and it says it spells rog.
i think the program itself has problem. not the coding.


#4

Can you put your current code here?


#5

animals = "catdogfrog"
cat = animals [:3] # The first three characters of animals
dog = animals [3:7] # The fourth through sixth characters
frog = animals [7:] # From the seventh character to the end

i even tried

animals = "catdogfrog"
cat = animals [:3] # The first three characters of animals
dog = animals [3:6] # The fourth through sixth characters
frog = animals [7:] # From the seventh character to the end

and all of the possible combinations...


#6

It's not about trying all possible combinations but to understand a concept using theory of the exercise(and other sources youre using) then following instruction that will help you get to correct code most of the times.

Your second code is almost okay except last line..

frog = animals [7:]

Given string is..
animals = "catdogfrog"

at index 0 -- > 'c' 
at index 1 -- > 'a'
at index 2 -- > 't'
at index 3 -- > 'd'
at index 4 -- > 'o'
at index 5 -- > 'g'
at index 6 -- > 'f'
at index 7 -- > 'r'
at index 8 -- > 'o'
at index 9 -- > 'g'

When we say item at 7th position in our language ,It means 6th position in Python's language because Python counts from 0 but we humans from 1.

I hope you will find the mistake now?If not,I'll help!


#7

okay, i got it the problem is the last line, but the error kept on showing the error came from the second line. I did grab the concept, it is just the error kept on redirecting me to the second line. thanks


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.