In the previous lesson, you saw how you could access individual characters in a string using indexing. In this lesson, you’ll learn how to expand that syntax to extract substrings from a string. This technique is known as string slicing. You’ll practice with the standard syntax, and learn how omitting the first or last index extends the slice. You’ll also learn how to specify a stride in a string slice by using a third index.
Here are some string slicing examples:
>>> s = 'mybacon'
>>> s[2:5]
'bac'
>>> s[2:7]
'bacon'
>>> s[0:2]
'my'
You can omit the first or last index:
>>> s = 'mybacon'
>>> s[:2]
'my'
>>> s[:5]
'mybac'
>>> s[2:]
'bacon'
>>> s[2:len(s)]
>>> s[:2] + s[2:]
'mybacon'
>>> s[:]
'mybacon'
>>> t = s[:]
>>> t
'mybacon'
>>> id(s)
4380975712
>>> id(t)
4380975712
>>> s == t
True
>>> s is t
True
>>> s[2:2]
''
>>> s[4:2]
''
Here’s some negative index slicing:
>>> s = 'mybacon'
>>> s[-5:-1]
'baco'
>>> s[2:6]
'baco'
Here’s how to slice with a stride:
>>> s = 'mybacon'
>>> s[0:7:2]
'mbcn'
>>> s[1:7:2]
'yao'
>>> s = '12345' * 5
>>> s
'1234512345123451234512345'
>>> s[::5]
'11111'
>>> s[4::5]
'55555'
>>> s[::-5]
'55555'
>>> s[::-1]
'5432154321543215432154321'
>>> s = 'tacocat'
>>> s == s[::-1]
True
>>> s[::-1]
'tacocat'
DoubleA on Jan. 24, 2021
Hello Chris! Thanks for sharing your knowledge. Here’s my code snippet:
When I run the above code I get
True
. However, when I modify the above code slightly and replace the equals==
operator by theis
object identity operator, the output I get isFalse
:My understanding is that the operator
is
returnsTrue
only and only if theid
of the two objects is the same (the source). In the above example, the call of theid()
object returns two identical integers.What is the reason for the above behaviour? Aren’the two string slices above “the same object”?