6. Slicing Lists and Strings


#1

“”“Why is it this code…”""

animals = “catdogfrog”

The first three characters of animals

cat = animals[:3]

The fourth through sixth characters

dog = animals[3:6]

From the seventh character to the end

frog = animals[6:]

“”“and not…”""

animals = “catdogfrog”

The first three characters of animals

cat = len(animals)[:3]

The fourth through sixth characters

dog = len(animals)[3:6]

From the seventh character to the end

frog = len(animals)[6:]

“”" Should it not have len to define the lenght of the word “catdogfrog”. I unndestand you dont put len when its “a, b,c “.””"


#2

This will result in an error since we cannot slice a number.

len(animals)  =>  10

cat = 10[:3]
>>> animals = 'catdogfrog'
>>> cat = len(animals)[:3]
Traceback (most recent call last):
  File "<pyshell#114>", line 1, in <module>
    cat = len(animals)[:3]
TypeError: 'int' object is not subscriptable
>>> 

#3

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