Week 9

Objects

In [2]:
mylist = [1, 2, 3]
In [4]:
len(mylist)
Out[4]:
3
In [5]:
mylist.append(4)
In [6]:
print(mylist)
[1, 2, 3, 4]

Compare with modules:

In [7]:
import math
In [8]:
math.pi
Out[8]:
3.141592653589793
In [9]:
math.sin(2)
Out[9]:
0.9092974268256817
In [10]:
dir(math)
Out[10]:
['__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'acos',
 'acosh',
 'asin',
 'asinh',
 'atan',
 'atan2',
 'atanh',
 'ceil',
 'copysign',
 'cos',
 'cosh',
 'degrees',
 'e',
 'erf',
 'erfc',
 'exp',
 'expm1',
 'fabs',
 'factorial',
 'floor',
 'fmod',
 'frexp',
 'fsum',
 'gamma',
 'gcd',
 'hypot',
 'inf',
 'isclose',
 'isfinite',
 'isinf',
 'isnan',
 'ldexp',
 'lgamma',
 'log',
 'log10',
 'log1p',
 'log2',
 'modf',
 'nan',
 'pi',
 'pow',
 'radians',
 'sin',
 'sinh',
 'sqrt',
 'tan',
 'tanh',
 'tau',
 'trunc']
In [11]:
help(math)
Help on module math:

NAME
    math

MODULE REFERENCE
    https://docs.python.org/3.6/library/math
    
    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    This module is always available.  It provides access to the
    mathematical functions defined by the C standard.

FUNCTIONS
    acos(...)
        acos(x)
        
        Return the arc cosine (measured in radians) of x.
    
    acosh(...)
        acosh(x)
        
        Return the inverse hyperbolic cosine of x.
    
    asin(...)
        asin(x)
        
        Return the arc sine (measured in radians) of x.
    
    asinh(...)
        asinh(x)
        
        Return the inverse hyperbolic sine of x.
    
    atan(...)
        atan(x)
        
        Return the arc tangent (measured in radians) of x.
    
    atan2(...)
        atan2(y, x)
        
        Return the arc tangent (measured in radians) of y/x.
        Unlike atan(y/x), the signs of both x and y are considered.
    
    atanh(...)
        atanh(x)
        
        Return the inverse hyperbolic tangent of x.
    
    ceil(...)
        ceil(x)
        
        Return the ceiling of x as an Integral.
        This is the smallest integer >= x.
    
    copysign(...)
        copysign(x, y)
        
        Return a float with the magnitude (absolute value) of x but the sign 
        of y. On platforms that support signed zeros, copysign(1.0, -0.0) 
        returns -1.0.
    
    cos(...)
        cos(x)
        
        Return the cosine of x (measured in radians).
    
    cosh(...)
        cosh(x)
        
        Return the hyperbolic cosine of x.
    
    degrees(...)
        degrees(x)
        
        Convert angle x from radians to degrees.
    
    erf(...)
        erf(x)
        
        Error function at x.
    
    erfc(...)
        erfc(x)
        
        Complementary error function at x.
    
    exp(...)
        exp(x)
        
        Return e raised to the power of x.
    
    expm1(...)
        expm1(x)
        
        Return exp(x)-1.
        This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
    
    fabs(...)
        fabs(x)
        
        Return the absolute value of the float x.
    
    factorial(...)
        factorial(x) -> Integral
        
        Find x!. Raise a ValueError if x is negative or non-integral.
    
    floor(...)
        floor(x)
        
        Return the floor of x as an Integral.
        This is the largest integer <= x.
    
    fmod(...)
        fmod(x, y)
        
        Return fmod(x, y), according to platform C.  x % y may differ.
    
    frexp(...)
        frexp(x)
        
        Return the mantissa and exponent of x, as pair (m, e).
        m is a float and e is an int, such that x = m * 2.**e.
        If x is 0, m and e are both 0.  Else 0.5 <= abs(m) < 1.0.
    
    fsum(...)
        fsum(iterable)
        
        Return an accurate floating point sum of values in the iterable.
        Assumes IEEE-754 floating point arithmetic.
    
    gamma(...)
        gamma(x)
        
        Gamma function at x.
    
    gcd(...)
        gcd(x, y) -> int
        greatest common divisor of x and y
    
    hypot(...)
        hypot(x, y)
        
        Return the Euclidean distance, sqrt(x*x + y*y).
    
    isclose(...)
        isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) -> bool
        
        Determine whether two floating point numbers are close in value.
        
           rel_tol
               maximum difference for being considered "close", relative to the
               magnitude of the input values
            abs_tol
               maximum difference for being considered "close", regardless of the
               magnitude of the input values
        
        Return True if a is close in value to b, and False otherwise.
        
        For the values to be considered close, the difference between them
        must be smaller than at least one of the tolerances.
        
        -inf, inf and NaN behave similarly to the IEEE 754 Standard.  That
        is, NaN is not close to anything, even itself.  inf and -inf are
        only close to themselves.
    
    isfinite(...)
        isfinite(x) -> bool
        
        Return True if x is neither an infinity nor a NaN, and False otherwise.
    
    isinf(...)
        isinf(x) -> bool
        
        Return True if x is a positive or negative infinity, and False otherwise.
    
    isnan(...)
        isnan(x) -> bool
        
        Return True if x is a NaN (not a number), and False otherwise.
    
    ldexp(...)
        ldexp(x, i)
        
        Return x * (2**i).
    
    lgamma(...)
        lgamma(x)
        
        Natural logarithm of absolute value of Gamma function at x.
    
    log(...)
        log(x[, base])
        
        Return the logarithm of x to the given base.
        If the base not specified, returns the natural logarithm (base e) of x.
    
    log10(...)
        log10(x)
        
        Return the base 10 logarithm of x.
    
    log1p(...)
        log1p(x)
        
        Return the natural logarithm of 1+x (base e).
        The result is computed in a way which is accurate for x near zero.
    
    log2(...)
        log2(x)
        
        Return the base 2 logarithm of x.
    
    modf(...)
        modf(x)
        
        Return the fractional and integer parts of x.  Both results carry the sign
        of x and are floats.
    
    pow(...)
        pow(x, y)
        
        Return x**y (x to the power of y).
    
    radians(...)
        radians(x)
        
        Convert angle x from degrees to radians.
    
    sin(...)
        sin(x)
        
        Return the sine of x (measured in radians).
    
    sinh(...)
        sinh(x)
        
        Return the hyperbolic sine of x.
    
    sqrt(...)
        sqrt(x)
        
        Return the square root of x.
    
    tan(...)
        tan(x)
        
        Return the tangent of x (measured in radians).
    
    tanh(...)
        tanh(x)
        
        Return the hyperbolic tangent of x.
    
    trunc(...)
        trunc(x:Real) -> Integral
        
        Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.

DATA
    e = 2.718281828459045
    inf = inf
    nan = nan
    pi = 3.141592653589793
    tau = 6.283185307179586

FILE
    /Users/bb1/anaconda/lib/python3.6/lib-dynload/math.cpython-36m-darwin.so


In [12]:
print(mylist)
[1, 2, 3, 4]
In [13]:
dir(mylist)
Out[13]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']
In [14]:
help(mylist)
Help on list object:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __iadd__(self, value, /)
 |      Implement self+=value.
 |  
 |  __imul__(self, value, /)
 |      Implement self*=value.
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.n
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __reversed__(...)
 |      L.__reversed__() -- return a reverse iterator over the list
 |  
 |  __rmul__(self, value, /)
 |      Return self*value.
 |  
 |  __setitem__(self, key, value, /)
 |      Set self[key] to value.
 |  
 |  __sizeof__(...)
 |      L.__sizeof__() -- size of L in memory, in bytes
 |  
 |  append(...)
 |      L.append(object) -> None -- append object to end
 |  
 |  clear(...)
 |      L.clear() -> None -- remove all items from L
 |  
 |  copy(...)
 |      L.copy() -> list -- a shallow copy of L
 |  
 |  count(...)
 |      L.count(value) -> integer -- return number of occurrences of value
 |  
 |  extend(...)
 |      L.extend(iterable) -> None -- extend list by appending elements from the iterable
 |  
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |  
 |  insert(...)
 |      L.insert(index, object) -- insert object before index
 |  
 |  pop(...)
 |      L.pop([index]) -> item -- remove and return item at index (default last).
 |      Raises IndexError if list is empty or index is out of range.
 |  
 |  remove(...)
 |      L.remove(value) -> None -- remove first occurrence of value.
 |      Raises ValueError if the value is not present.
 |  
 |  reverse(...)
 |      L.reverse() -- reverse *IN PLACE*
 |  
 |  sort(...)
 |      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None

In [15]:
mylist.index(3)
Out[15]:
2
In [16]:
dir(2)
Out[16]:
['__abs__',
 '__add__',
 '__and__',
 '__bool__',
 '__ceil__',
 '__class__',
 '__delattr__',
 '__dir__',
 '__divmod__',
 '__doc__',
 '__eq__',
 '__float__',
 '__floor__',
 '__floordiv__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__index__',
 '__init__',
 '__init_subclass__',
 '__int__',
 '__invert__',
 '__le__',
 '__lshift__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__neg__',
 '__new__',
 '__or__',
 '__pos__',
 '__pow__',
 '__radd__',
 '__rand__',
 '__rdivmod__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rfloordiv__',
 '__rlshift__',
 '__rmod__',
 '__rmul__',
 '__ror__',
 '__round__',
 '__rpow__',
 '__rrshift__',
 '__rshift__',
 '__rsub__',
 '__rtruediv__',
 '__rxor__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__sub__',
 '__subclasshook__',
 '__truediv__',
 '__trunc__',
 '__xor__',
 'bit_length',
 'conjugate',
 'denominator',
 'from_bytes',
 'imag',
 'numerator',
 'real',
 'to_bytes']
In [20]:
(1000).bit_length()
Out[20]:
10
In [21]:
2 + 3
Out[21]:
5
In [22]:
(2).__add__(3)
Out[22]:
5
In [23]:
mylist2 = [5, 6, 7]
In [24]:
mylist
Out[24]:
[1, 2, 3, 4]
In [25]:
mylist + mylist2
Out[25]:
[1, 2, 3, 4, 5, 6, 7]
In [26]:
mylist.__add__(mylist2)
Out[26]:
[1, 2, 3, 4, 5, 6, 7]
In [27]:
def f(n, m=5):
    return n*m
In [28]:
f(10)
Out[28]:
50
In [29]:
dir(f)
Out[29]:
['__annotations__',
 '__call__',
 '__class__',
 '__closure__',
 '__code__',
 '__defaults__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__get__',
 '__getattribute__',
 '__globals__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__kwdefaults__',
 '__le__',
 '__lt__',
 '__module__',
 '__name__',
 '__ne__',
 '__new__',
 '__qualname__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__']
In [30]:
f.__defaults__
Out[30]:
(5,)
In [31]:
f.__defaults__ = (2, 7)
In [32]:
f(10)
Out[32]:
70
In [33]:
f()
Out[33]:
14

File operations

The open() function opens a file. The argument "w" opens the file for writing. If a file with a specified name does not exist it will be created. If it exists its content will be overwritten.

In [34]:
myfile = open('test_file.txt', 'w')
In [35]:
s = "This is a test"
myfile.write(s)
myfile.close()

\n is the new line character:

In [40]:
s = "hello\nthere"
In [41]:
print(s)
hello
there
In [42]:
myfile = open('test_file.txt', 'w')
s = "Twinkle, twinkle little star\nHow I wonder what you are."
myfile.write(s)
Out[42]:
55
In [43]:
myfile.close()

Open a file with the argument "a" to append to it:

In [44]:
myfile = open('test_file.txt', 'a')
myfile.write("Up above the world so high\nLike a diamond in the sky.")
Out[44]:
53
In [45]:
myfile.close()
In [46]:
myfile = open('test_file.txt', 'r')
In [47]:
myfile.read(10)
Out[47]:
'Twinkle, t'

A file object remembers its current position. The tell() function can be used to get the current position in the file:

In [48]:
myfile.tell()
Out[48]:
10
In [49]:
myfile.read(15)
Out[49]:
'winkle little s'
In [50]:
myfile.tell()
Out[50]:
25

The seek() function can be used to change the current position in the file:

In [51]:
myfile.seek(0)
myfile.read(10)
Out[51]:
'Twinkle, t'

read() without argument reads the whole file starting at the current position:

In [52]:
myfile.seek(0)
myfile.read()
Out[52]:
'Twinkle, twinkle little star\nHow I wonder what you are.Up above the world so high\nLike a diamond in the sky.'
In [53]:
myfile.seek(0)
print(myfile.read())
Twinkle, twinkle little star
How I wonder what you are.Up above the world so high
Like a diamond in the sky.

readlines() function returns a list of all lines of the file (starting from the current position):

In [54]:
print(myfile.read())

In [55]:
myfile.seek(0)
print(myfile.readlines())
['Twinkle, twinkle little star\n', 'How I wonder what you are.Up above the world so high\n', 'Like a diamond in the sky.']
In [56]:
myfile.seek(0)
lines = myfile.readlines()
In [57]:
lines[1]
Out[57]:
'How I wonder what you are.Up above the world so high\n'
In [58]:
myfile.close()

Requests

requests is a module from communicationg with webpages:

In [2]:
import requests
In [3]:
ubmath = requests.get('http://www.math.buffalo.edu')
In [61]:
dir(ubmath)
Out[61]:
['__attrs__',
 '__bool__',
 '__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getstate__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__nonzero__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__setstate__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 '_content',
 '_content_consumed',
 'apparent_encoding',
 'close',
 'connection',
 'content',
 'cookies',
 'elapsed',
 'encoding',
 'headers',
 'history',
 'is_permanent_redirect',
 'is_redirect',
 'iter_content',
 'iter_lines',
 'json',
 'links',
 'ok',
 'raise_for_status',
 'raw',
 'reason',
 'request',
 'status_code',
 'text',
 'url']
In [62]:
print(ubmath.headers)
{'Date': 'Tue, 24 Oct 2017 13:57:06 GMT', 'Server': 'Apache/2.4.6 () Communique/4.2.0 OpenSSL/1.0.2k-fips', 'Last-Modified': 'Tue, 24 Oct 2017 13:57:04 GMT', 'ETag': '"159d8-55c4b5062d2bb-gzip"', 'Accept-Ranges': 'bytes', 'Vary': 'Accept-Encoding,User-Agent', 'Content-Encoding': 'gzip', 'Cache-Control': 'max-age=10', 'Expires': 'Tue, 24 Oct 2017 13:57:16 GMT', 'Content-Length': '14586', 'Keep-Alive': 'timeout=5, max=100', 'Connection': 'Keep-Alive', 'Content-Type': 'text/html; charset=UTF-8'}
In [4]:
print(ubmath.text[:1000])
<!DOCTYPE HTML><html lang="en"><!-- cmspub02 1027-171408 -->
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta id="meta-viewport" name="viewport" content="width=device-width,initial-scale=1">
        <script>if (screen.width > 720 && screen.width < 960) document.getElementById('meta-viewport').setAttribute('content','width=960');</script>
    <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-T5KRRKT');</script><title>Department of Mathematics - Department of Mathematics  - University at Buffalo</title>
    <meta name="keywords" content="">
    <meta name="keywordIDs" content="">
    <meta name="description" con
In [5]:
verne = requests.get('http://www.gutenberg.org/cache/epub/103/pg103.txt').text
In [6]:
verne[:1000]
Out[6]:
'\ufeffThe Project Gutenberg EBook of Around the World in 80 Days, by Jules Verne\r\n\r\nThis eBook is for the use of anyone anywhere at no cost and with\r\nalmost no restrictions whatsoever.  You may copy it, give it away or\r\nre-use it under the terms of the Project Gutenberg License included\r\nwith this eBook or online at www.gutenberg.net\r\n\r\n\r\nTitle: Around the World in 80 Days\r\n\r\nAuthor: Jules Verne\r\n\r\nRelease Date: May 15, 2008 [EBook #103]\r\nLast updated: February 18, 2012\r\nLast updated: May 5, 2012\r\n\r\nLanguage: English\r\n\r\n\r\n*** START OF THIS PROJECT GUTENBERG EBOOK AROUND THE WORLD IN 80 DAYS ***\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nAROUND THE WORLD IN EIGHTY DAYS\r\n\r\n\r\n\r\nCONTENTS\r\n\r\n\r\nCHAPTER\r\n\r\n      I  IN WHICH PHILEAS FOGG AND PASSEPARTOUT ACCEPT EACH OTHER, THE\r\n         ONE AS MASTER, THE OTHER AS MAN\r\n\r\n     II  IN WHICH PASSEPARTOUT IS CONVINCED THAT HE HAS AT LAST FOUND\r\n         HIS IDEAL\r\n\r\n    III  IN WHICH A CONVERSATION TAKES PLACE WHICH SEEMS LIKELY TO COST\r\n         PHILEAS FOGG DEAR\r\n\r\n'

Note: Microsoft Windows computers use \r\n to encode the new line in text.

In [67]:
s = 'beginning\rEND'
print(s)
END
In [7]:
print(verne[:1000])
The Project Gutenberg EBook of Around the World in 80 Days, by Jules Verne

This eBook is for the use of anyone anywhere at no cost and with
almost no restrictions whatsoever.  You may copy it, give it away or
re-use it under the terms of the Project Gutenberg License included
with this eBook or online at www.gutenberg.net


Title: Around the World in 80 Days

Author: Jules Verne

Release Date: May 15, 2008 [EBook #103]
Last updated: February 18, 2012
Last updated: May 5, 2012

Language: English


*** START OF THIS PROJECT GUTENBERG EBOOK AROUND THE WORLD IN 80 DAYS ***













AROUND THE WORLD IN EIGHTY DAYS



CONTENTS


CHAPTER

      I  IN WHICH PHILEAS FOGG AND PASSEPARTOUT ACCEPT EACH OTHER, THE
         ONE AS MASTER, THE OTHER AS MAN

     II  IN WHICH PASSEPARTOUT IS CONVINCED THAT HE HAS AT LAST FOUND
         HIS IDEAL

    III  IN WHICH A CONVERSATION TAKES PLACE WHICH SEEMS LIKELY TO COST
         PHILEAS FOGG DEAR


String functions

replace()

The replace function replaces a substring in a string with another substring:

In [69]:
poem = "Twinkle, twinkle, little star\nHow I wonder what you are"
In [70]:
print(poem)
Twinkle, twinkle, little star
How I wonder what you are
In [71]:
new_poem = poem.replace('\n', ' ***NEW_LINE*** ')
In [72]:
print(new_poem)
Twinkle, twinkle, little star ***NEW_LINE*** How I wonder what you are
In [73]:
twinkle = poem.replace('\n', ' ')
In [74]:
print(twinkle)
Twinkle, twinkle, little star How I wonder what you are

split()

The split() function splits a string along all occurences of specified substring and returns a list of the strings obtained in this way:

In [75]:
print(twinkle)
Twinkle, twinkle, little star How I wonder what you are
In [76]:
words = twinkle.split(' ')
In [77]:
print(words)
['Twinkle,', 'twinkle,', 'little', 'star', 'How', 'I', 'wonder', 'what', 'you', 'are']
In [78]:
parts = twinkle.split('tt')
print(parts)
['Twinkle, twinkle, li', 'le star How I wonder what you are']
In [79]:
s = "This is a       test"
In [80]:
print(s.split(' '))
['This', 'is', 'a', '', '', '', '', '', '', 'test']
In [81]:
print(s.split())
['This', 'is', 'a', 'test']

join()

The join() function joins a list of strings:

In [82]:
print(words)
['Twinkle,', 'twinkle,', 'little', 'star', 'How', 'I', 'wonder', 'what', 'you', 'are']
In [83]:
'__'.join(words)
Out[83]:
'Twinkle,__twinkle,__little__star__How__I__wonder__what__you__are'
In [84]:
' '.join(words)
Out[84]:
'Twinkle, twinkle, little star How I wonder what you are'
In [85]:
''.join(words)
Out[85]:
'Twinkle,twinkle,littlestarHowIwonderwhatyouare'

find()

In [86]:
print(twinkle)
Twinkle, twinkle, little star How I wonder what you are
In [87]:
'little star' in twinkle
Out[87]:
True
In [88]:
'little duck' in twinkle
Out[88]:
False

The find() function is searching for a substring in a string. It the substring is found it returns the index where the substring starts. If it is not found it returns -1.

In [89]:
found = twinkle.find('little star')
In [90]:
print(found)
18
In [91]:
twinkle.find('t')
Out[91]:
9
In [92]:
verne.find('ocean')
Out[92]:
40489
In [93]:
print(verne[40489: 40489+300])
ocean steamers to be
two or three days behind time?  But a single delay would suffice to
fatally break the chain of communication; should Phileas Fogg once
miss, even by an hour; a steamer, he would have to wait for the next,
and that would irrevocably render his attempt vain.

This article ma
In [94]:
verne_lines = verne.split('\r\n')
In [95]:
verne_lines[300]
Out[95]:
'error.  Now from this moment, twenty-nine minutes after eleven, a.m.,'
In [97]:
for line in verne_lines:
    if line.find('ocean')  != -1:
        print(line + '\n')
the winds and fogs?  Is it uncommon for the best ocean steamers to be

upon the ocean, darkening now with the twilight, on which she had

phosphorescent scintillations of the ocean.

would cross the ocean in twenty-one days.  Phileas Fogg was therefore

"From ocean to ocean"--so say the Americans; and these four words

In [98]:
for line in verne_lines:
    if line.find('Ocean')  != -1:
        print(line + '\n')
Ocean, and the vast cisterns where the English engineers were still at

the Indian Ocean.  She had a hundred and sixty-eight hours in which to

of Bengal does not agree with me as well as the Indian Ocean.  And how

The lower() function returns a string converted to lowercase. The upper() returns a string converted to upper case:

In [99]:
s = 'This is Bob.'
In [100]:
print(s.lower())
this is bob.
In [101]:
print(s.upper())
THIS IS BOB.
In [104]:
for line in verne_lines:
    lowline = line.lower()
    if lowline.find('ocean') != -1:
        print(line + '\n')
     IX  IN WHICH THE RED SEA AND THE INDIAN OCEAN PROVE PROPITIOUS

  XXIV  DURING WHICH MR. FOGG AND PARTY CROSS THE PACIFIC OCEAN

the winds and fogs?  Is it uncommon for the best ocean steamers to be

IN WHICH THE RED SEA AND THE INDIAN OCEAN PROVE PROPITIOUS TO THE

Ocean, and the vast cisterns where the English engineers were still at

the Indian Ocean.  She had a hundred and sixty-eight hours in which to

of Bengal does not agree with me as well as the Indian Ocean.  And how

upon the ocean, darkening now with the twilight, on which she had

phosphorescent scintillations of the ocean.

DURING WHICH MR. FOGG AND PARTY CROSS THE PACIFIC OCEAN

would cross the ocean in twenty-one days.  Phileas Fogg was therefore

"From ocean to ocean"--so say the Americans; and these four words

Project 6

The ord() function returns the ascii code of a character:

In [2]:
msg = 'Secret!!!'
for c in msg:
    print(ord(c))
83
101
99
114
101
116
33
33
33

The chr() function converts ascii codes into corresponding characters:

In [3]:
mylist = [83, 101, 99, 114, 101, 116, 33, 33, 33]
for n in mylist:
    print(chr(n))
S
e
c
r
e
t
!
!
!
In [4]:
charlist = [chr(n) for n in mylist]
print(charlist)
['S', 'e', 'c', 'r', 'e', 't', '!', '!', '!']
In [5]:
''.join(charlist)
Out[5]:
'Secret!!!'