COP3990C - Python Programming


In [1]:
from IPython.core.display import HTML
def css_styling():
    styles = open("styles/custom.css", "r").read()
    return HTML(styles)
css_styling()


Out[1]:

Strings


In [1]:
# create a string
str = '   the quick brown fox jumps over the lazy dog. '
str


Out[1]:
'   the quick brown fox jumps over the lazy dog. '

In [2]:
# this is an empty string
empty_str = ''

In [3]:
# strip whitespaces from the beginning and ending of the string
str2=str.strip()
print str2
print str


the quick brown fox jumps over the lazy dog.
   the quick brown fox jumps over the lazy dog. 

In [5]:
# this capitalizes the 1st letter of the string
str2.capitalize()


Out[5]:
'The quick brown fox jumps over the lazy dog.'

In [6]:
# count the number of occurrences for the string o
str.count('o')


Out[6]:
4

In [7]:
# check if a string ends with a certain character
str2.endswith('.')


Out[7]:
True

In [53]:
# check if a substring exists in the string
'jum' in str


Out[53]:
True

In [9]:
# find the index of the first occurrence  
str.find('fox')


Out[9]:
19

In [10]:
# let's see what character is at index 19
str[19]


Out[10]:
'f'

Lists and Strings

Note: strings are immutable while lists are not. In other words immutability does not allow for in-place modification of the object.

"Also notice in the prior examples that we were not changing the original string with any of the operations we ran on it. Every string operation is defined to produce a new string as its result, because strings are immutable in Python—they cannot be chang ed in place after they are created. In other words, you can never overwrite the values of immutable objects. For example, you can’t change a string by assigning to one of its positions, but you can always build a new one and assign it to the same name. Because Python cleans up old objects as you go (as you’ll see later), this isn’t as inefficient as it may sound:"

In [11]:
S = 'shrubbery' 
S[1]='c'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-b22ad8005f58> in <module>()
      1 S = 'shrubbery'
----> 2 S[1]='c'

TypeError: 'str' object does not support item assignment


In [55]:
S = 'shrubbery' 
L = list(S)
L


Out[55]:
['s', 'h', 'r', 'u', 'b', 'b', 'e', 'r', 'y']

In [56]:
S[0]


Out[56]:
's'

In [61]:
L[1] = 'c'
print L
S1 = ''.join(L)
print 'this is S1:', S1
print S


['s', 'c', 'r', 'u', 'b', 'b', 'e', 'r', 'y']
this is S1: scrubbery
scrubbery

In [57]:
for x in S:
    print x


s
h
r
u
b
b
e
r
y

In [60]:
# another way of changing the string 
S = S[0] + 'c' + S[2:] # string concatenation
S


I like python
Out[60]:
'scrubbery'

In [15]:
# 
line = 'aaa,bbb,cccc c,dd'
line1 = line.split(',') 
print line
print line1


aaa,bbb,cccc c,dd
['aaa', 'bbb', 'cccc c', 'dd']

In [16]:
dir(S)


Out[16]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__getslice__',
 '__gt__',
 '__hash__',
 '__init__',
 '__le__',
 '__len__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmod__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '_formatter_field_name_split',
 '_formatter_parser',
 'capitalize',
 'center',
 'count',
 'decode',
 'encode',
 'endswith',
 'expandtabs',
 'find',
 'format',
 'index',
 'isalnum',
 'isalpha',
 'isdigit',
 'islower',
 'isspace',
 'istitle',
 'isupper',
 'join',
 'ljust',
 'lower',
 'lstrip',
 'partition',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rpartition',
 'rsplit',
 'rstrip',
 'split',
 'splitlines',
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',
 'zfill']

In [17]:
help(S.split)


Help on built-in function split:

split(...)
    S.split([sep [,maxsplit]]) -> list of strings
    
    Return a list of the words in the string S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are removed
    from the result.


In [18]:
ord(S[0])


Out[18]:
115

Dictionaries


In [10]:
# empty dictionary
D = {}

In [11]:
D['food'] = 'Spam'
D['quantity'] = 4
D['color']='pink'
D


Out[11]:
{'color': 'pink', 'food': 'Spam', 'quantity': 4}

In [12]:
# another way to declare a dictionary
D = {'food': 'Spam', 'quantity': 4, 'color': 'pink'}
print D
D[0] = 'ZERO'
print D


{'food': 'Spam', 'color': 'pink', 'quantity': 4}
{'food': 'Spam', 'color': 'pink', 0: 'ZERO', 'quantity': 4}

In [13]:
D['somthing'] = 'another'

In [65]:
D[0]


Out[65]:
'ZERO'

In [14]:
print D


{'food': 'Spam', 'color': 'pink', 'somthing': 'another', 0: 'ZERO', 'quantity': 4}

In [23]:
# print the value associated with the key 'food'
D['food']


Out[23]:
'Spam'

In [24]:
# there is no restrictions on the key type
D = {1:'1', 2:'2'}
print D


{1: '1', 2: '2'}

In [25]:
bob1 = dict(name='Bob', job='dev', age=40)
print bob1


{'age': 40, 'job': 'dev', 'name': 'Bob'}

In [26]:
bob2 = dict(zip(['name', 'job', 'age'], ['Bob', 'dev', 40]))
print bob2


{'age': 40, 'job': 'dev', 'name': 'Bob'}

In [6]:
# nesting - no restrictions on value
rec = {'name': {'first': ['bob', 'mob'], 'last': 'Smith'},
           'jobs': ['dev', 'mgr'],
           'age':  40.5}
print rec


{'age': 40.5, 'jobs': ['dev', 'mgr'], 'name': {'last': 'Smith', 'first': ['bob', 'mob']}}

In [7]:
# access the first element
rec['name']


Out[7]:
{'first': ['bob', 'mob'], 'last': 'Smith'}

In [8]:
rec['name']['first']


Out[8]:
['bob', 'mob']

In [9]:
rec['name']['first'][0]


Out[9]:
'bob'
Tuples - Immutable lists

In [ ]:
# empty tuple
T = ()

In [37]:
# definition
T= (1, 2, 3, 4)
print T


(1, 2, 3, 4)

In [39]:
# get the first element of T just like you would with lists
T[0]


Out[39]:
1

In [43]:
# add two tuples to make a larger tuple
T+(5,6)


Out[43]:
(1, 2, 3, 4, 5, 6)

In [47]:
# you can't just one element to the typle unless that element is a tuple
T + 7


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-47-c2b728d0541f> in <module>()
      1 # you can't just one element to the typle unless that element is a tuple
----> 2 T + 7

TypeError: can only concatenate tuple (not "int") to tuple

In [48]:
# here's how you add the 7 to the tuple
T + (7,)


Out[48]:
(1, 2, 3, 4, 7)

In [49]:
# here's how you add a string to the tuple
T + ('abc',)


Out[49]:
(1, 2, 3, 4, 'abc')
Files

In [32]:
!dir


 Volume in drive C has no label.
 Volume Serial Number is 92E0-AA74

 Directory of C:\Users\User\Dropbox\UWF\spring2014\Python\UWF_2014_spring_COP3990C-2507\notebooks

01/15/2014  12:03 PM    <DIR>          .
01/15/2014  12:03 PM    <DIR>          ..
01/13/2014  02:58 AM    <DIR>          .ipynb_checkpoints
01/13/2014  09:22 AM    <DIR>          images
01/13/2014  08:13 AM            21,727 Lecture 01 - Introduction.ipynb
01/15/2014  10:09 AM            20,778 Lecture 04 - more on datatypes.ipynb
01/15/2014  09:41 AM            43,585 Lecture 3 - Data Types.ipynb
01/13/2014  08:11 AM                10 README.md
01/13/2014  02:58 AM    <DIR>          styles
01/15/2014  12:03 PM               824 test
               5 File(s)         86,924 bytes
               5 Dir(s)  314,656,518,144 bytes free

In [33]:
f = open('test','r')

In [34]:
lines = f.readlines()
lines


Out[34]:
[' Volume in drive C has no label.\n',
 ' Volume Serial Number is 92E0-AA74\n',
 '\n',
 ' Directory of C:\\Users\\User\\Dropbox\\UWF\\spring2014\\Python\\UWF_2014_spring_COP3990C-2507\\notebooks\n',
 '\n',
 '01/15/2014  12:03 PM    <DIR>          .\n',
 '01/15/2014  12:03 PM    <DIR>          ..\n',
 '01/13/2014  02:58 AM    <DIR>          .ipynb_checkpoints\n',
 '01/13/2014  09:22 AM    <DIR>          images\n',
 '01/13/2014  08:13 AM            21,727 Lecture 01 - Introduction.ipynb\n',
 '01/15/2014  10:09 AM            20,778 Lecture 04 - more on datatypes.ipynb\n',
 '01/15/2014  09:41 AM            43,585 Lecture 3 - Data Types.ipynb\n',
 '01/13/2014  08:11 AM                10 README.md\n',
 '01/13/2014  02:58 AM    <DIR>          styles\n',
 '01/15/2014  12:03 PM                 0 test\n',
 '               5 File(s)         86,100 bytes\n',
 '               5 Dir(s)  314,656,653,312 bytes free\n']

In [50]:
f.close()

In [35]:
print lines[0]


 Volume in drive C has no label.


In [36]:
for line in lines:
    print line


 Volume in drive C has no label.

 Volume Serial Number is 92E0-AA74



 Directory of C:\Users\User\Dropbox\UWF\spring2014\Python\UWF_2014_spring_COP3990C-2507\notebooks



01/15/2014  12:03 PM    <DIR>          .

01/15/2014  12:03 PM    <DIR>          ..

01/13/2014  02:58 AM    <DIR>          .ipynb_checkpoints

01/13/2014  09:22 AM    <DIR>          images

01/13/2014  08:13 AM            21,727 Lecture 01 - Introduction.ipynb

01/15/2014  10:09 AM            20,778 Lecture 04 - more on datatypes.ipynb

01/15/2014  09:41 AM            43,585 Lecture 3 - Data Types.ipynb

01/13/2014  08:11 AM                10 README.md

01/13/2014  02:58 AM    <DIR>          styles

01/15/2014  12:03 PM                 0 test

               5 File(s)         86,100 bytes

               5 Dir(s)  314,656,653,312 bytes free


In [ ]: