Professional Documents
Culture Documents
Session1 1
Session1 1
Session1 1
In [1]:
x=10
In [2]:
y=20
You can view a list of all the variables in the notebook using the magic command %whos.
In [8]:
%whos
In [5]:
whos
In [6]:
x=5
In [7]:
whos
In [9]:
%whos
In [10]:
x='a'
In [39]:
%whos
In [40]:
del s
In [41]: %whos
Strings
In [13]:
s=" "
In [14]:
print(s)
In [16]:
type(s)
str
Out[16]:
In [2]:
w = "Hello World"
In [3]:
print(w)
Hello World
In [4]:
type(w)
str
Out[4]:
A string is an array of characters, therfore it has length to indicate the size of the string. For example,
we could check the size of the string by using the built-in function len.
In [5]:
len(w)
11
Out[5]:
Strings also have indexes to indicate the location of each character, so that we could easily find out
some character. The index of the position start with 0
Indexing
H|e|l|l|o| |W|o|r|l|d
0|1|2|3|4|5|6|7|8|9|10
In [6]:
w[6]
Out[6]: 'W'
Negative indices- count backward from the end ofthe string. The expression w[-1] yields the last
letter, w[-2] yields the second to last, and so on
In [7]:
w[-1]
'd'
Out[7]:
In [9]:
w[-2]
'l'
Out[9]:
string slicing
In [20]:
w[6:11]
'World'
Out[20]:
[6:11] means the start position is from index 6 and the end position is index 10. For Python string
slicing range, the upper-bound is exclusive, which means that [6:11] is actually to slice the characters
from 6 -> 10
If you omit the first index (before the colon), the slice starts at the beginning of the string. If you
omit the second index, the slice goes to the end of the string:
In [21]:
w[6:]
'World'
Out[21]:
In [22]:
w[5:]
' World'
Out[22]:
In [23]:
w[:5]
'Hello'
Out[23]:
If the first index is greater than or equal to the second the result is an empty string, represented by
two quotation marks:
In [12]:
w[5:5]
''
Out[12]:
In [13]:
w[:]
In [14]:
w[-6:-2]
' Wor'
Out[14]:
In [24]:
w[6:-2]
'Wor'
Out[24]:
You can also use negative index when slice the strings, which means counting from the end of the
string. For example, -1 means the last character, -2 means the 2nd to last and so on
In [26]:
w[6:-1]
'Worl'
Out[26]:
In [28]:
w[6:-3]
'Wo'
Out[28]:
In [29]:
w[6:0]
''
Out[29]:
In [31]:
w[4:-1]
'o Worl'
Out[31]:
In [32]:
w[::2] #Hello World
'HloWrd'
Out[32]:
In [33]:
w[::3] #If you want every 3rd element
'HlWl'
Out[33]:
In [15]:
w[1::3]
'eood'
Out[15]:
In [16]:
w[::-1]
'dlroW olleH'
Out[16]:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_936/4025190968.py in <module>
----> 1 w[0]='j'
In [23]:
w='Hello World'
w='J'+w[1:]
print(w)
Jello World
The word in is a boolean operator that takes two strings and returns True if the first appears as a
substring in the second:
In [24]:
'e' in w
True
Out[24]:
In [ ]: