Imports and modules


In [3]:
import numpy as np

In [5]:
from numpy import pi

In [7]:
from numpy import *

In [8]:
import numpy.linalg as la

In [2]:
numpy.pi


Out[2]:
3.141592653589793

In [4]:
np.pi


Out[4]:
3.141592653589793

In [6]:
pi


Out[6]:
3.141592653589793

Files


In [23]:
%%file foo.py
def bar():
    print('hi')
    
if __name__ == '__main__':
    bar()


Overwriting foo.py

In [10]:
! ls


foo.py	Lecture01.ipynb  Lecture02.ipynb  Lecture03.ipynb

In [11]:
import foo

In [13]:
foo.bar()


hi

In [14]:
from foo import bar

In [15]:
bar()


hi

In [17]:
! python foo.py


hi

In [18]:
f = open('foo.py', 'r')
print(f.read())
f.close()


def bar():
    print('hi')
    
if __name__ == '__main__':
    bar()

In [20]:
with open('foo.py', 'r') as f:
    print(f.read())


def bar():
    print('hi')
    
if __name__ == '__main__':
    bar()

Strings


In [24]:
with open('foo.py', 'r') as f:
    lines = f.readlines()

In [25]:
lines


Out[25]:
['def bar():\n',
 "    print('hi')\n",
 '    \n',
 "if __name__ == '__main__':\n",
 '    bar()']

In [26]:
line = lines[0]

In [27]:
line


Out[27]:
'def bar():\n'

In [30]:
line = line.strip()

In [31]:
line


Out[31]:
'def bar():'

In [32]:
line.lower()


Out[32]:
'def bar():'

In [33]:
line.upper()


Out[33]:
'DEF BAR():'

In [34]:
line.title()


Out[34]:
'Def Bar():'

In [35]:
lines


Out[35]:
['def bar():\n',
 "    print('hi')\n",
 '    \n',
 "if __name__ == '__main__':\n",
 '    bar()']

In [36]:
''.join(lines)


Out[36]:
"def bar():\n    print('hi')\n    \nif __name__ == '__main__':\n    bar()"

In [37]:
'XXX'.join(lines)


Out[37]:
"def bar():\nXXX    print('hi')\nXXX    \nXXXif __name__ == '__main__':\nXXX    bar()"

In [39]:
fubar = '-'.join(['foo', 'bar', 'baz'])

In [40]:
fubar


Out[40]:
'foo-bar-baz'

In [41]:
fubar.split('-')


Out[41]:
['foo', 'bar', 'baz']

In [43]:
s = ''.join(lines)
s.split()


Out[43]:
['def',
 'bar():',
 "print('hi')",
 'if',
 '__name__',
 '==',
 "'__main__':",
 'bar()']

In [47]:
from string import punctuation

In [48]:
punctuation


Out[48]:
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

In [51]:
s = ''.join(lines)

In [52]:
s


Out[52]:
"def bar():\n    print('hi')\n    \nif __name__ == '__main__':\n    bar()"

In [53]:
for char in punctuation:
    s = s.replace(char, '')

In [54]:
s


Out[54]:
'def bar\n    printhi\n    \nif name  main\n    bar'

In [55]:
s = ''.join(lines)

In [56]:
table = dict.fromkeys(map(ord, punctuation))

In [58]:
s


Out[58]:
"def bar():\n    print('hi')\n    \nif __name__ == '__main__':\n    bar()"

In [59]:
s.translate(table)


Out[59]:
'def bar\n    printhi\n    \nif name  main\n    bar'

In [62]:
s


Out[62]:
"def bar():\n    print('hi')\n    \nif __name__ == '__main__':\n    bar()"

In [63]:
s[5:10]


Out[63]:
'ar():'

In [65]:
s.find('bar')


Out[65]:
4

In [66]:
s.rfind('bar')


Out[66]:
63

Regular expressions


In [ ]: