Lecture 2 Flashcards
In terms of strings, what is slicing?
String is an ordered sequence of characters, and therefore we can retrieve the elements of this sequence by referring to their indices.
How to slice a string?
Use the name of string to be sliced followed by square bracktes with the index of the position we want to return.
~~~
»> str1 = ‘home’
»> str1[1]
o
~~~
How to get last element from a string without knowing how long it is?
Use index -1 when slicing
What happens if I slice using an index that is greater than the length of string minus 1?
I will get an IndexError (see below)
Is it possible to slice more than one character from a string?
string_name[start:stop:step]
Remember: Python will include start index but will stop at stop-1 index.
What is the output from the prompt below?
>>> s = 'abcdefgh' >>> s[3:6:2]
‘df’
What is the output from the prompt below?
>>> s = 'abcdefgh' >>> s[::-1]
‘hgfedcba’
What is the output from the prompt below?
>>> s = 'abcdefgh' >>> s[4:1:-2]
‘ec’
What is the output from the prompt below?
>>> s = 'ABC d3f ghi' >>> s[6:3]
''
- empty string
- Start position is f.
- Step is not specified so it is set to 1 by default.
- Stopping position is the first space.
As we are moving to the right (step=1) but stopping point is to the left, there are no characters to return.
Are strings mutable or immutable? What does it mean?
Strings are immutable, meaning I cannot change one of its element by value assignment after it has been created.
What is Operator Overloading? Explain it through an example.
Operator overloading is when an operator behaves differently depending on the object to which it is applied.
For example, the +
operator will add two numbers together but it will concatenate strings instead of throwing an error.
~~~
»> “a” + “a”
aa
»> 1 + 2
3
~~~
The *
operator is also overloaded, since it is multiplication for number but repetition for strings.
What is the outcome from typing the command below in the interpreter?
~~~
»> new_id
~~~
Moreover, explain how Python handles this command.
It results in a NameError.NameError: name 'new_id' is not defined
new_id
is not a literal from any built-in type. It is then assumed to be a name, but since it is no bound to any object, Python throws an error since names can only exist bound to an object.