Cordelia Williams
Cordelia Williams

Reputation: 151

Basic Slicing Review

I am confused as to what is done when there are two slicing operations right next to each other. For example:

>>> s = 'Fuzzy wuzzy was a bear'
>>> L = s.split()
>>> u = L[-1][:2]
'be'

I have no idea why it returns this output? And how to interpret it when there are slices [][] right next to eachother. Thank you.

Upvotes: 0

Views: 70

Answers (4)

jamylak
jamylak

Reputation: 133724

Your question has been answered, now for the most efficient way to do this:

>>> s.rpartition(' ')[-1][:2]
'be'

This doesn't need to split every single world like s.split() with no arguments.

>>> help(str.rpartition)
Help on method_descriptor:

rpartition(...)
    S.rpartition(sep) -> (head, sep, tail)

    Search for the separator sep in S, starting at the end of S, and return
    the part before it, the separator itself, and the part after it.  If the
    separator is not found, return two empty strings and S.

Upvotes: 0

Pep_8_Guardiola
Pep_8_Guardiola

Reputation: 5252

They work in order, one after the other.

L[-1] gives you the last item in L

[:2] gives you the first two elements.

So, L[-1][:2] gives you the first two elements of the last item in L.

Upvotes: 0

Ankur Ankan
Ankur Ankan

Reputation: 3066

 >>>s = 'Fuzzy wuzzy was a bear'
 >>>L = s.split()

Here L is a list: L = ['Fuzzy', 'wuzzy', 'was', 'a', 'bear']

 >>>u = L[-1][:2]
 'be'

Now when you do L[-1][:2] it first does L[-1] which returns 'bear' and then the slicing operation [:2] is done which returns 'be'.

Upvotes: 0

user1907906
user1907906

Reputation:

First you split the string by whitespace which results in a list of 'words'.

s = 'Fuzzy wuzzy was a bear'
L = s.split()
# L == ['Fuzzy', 'wuzzy', 'was', 'a', 'bear']

The last of these 'words' is taken by [-1]:

m = L[-1]
# m == 'bear'

Of this word the first two characters are taken by [:2]:

u = m[:2]
# u == 'be'

Upvotes: 3

Related Questions