str
print
open
and with
Reading material:
str(...)
, '...'
, "..."
, """..."""
, '''...'''
, etc.'...'.format(...)
'...'
and double quotes "..."
as delimiters"
or single '
quotes in a string'\''
print('Single "quoted" string.')
print("Double 'quoted' string.")
print('This let\'s us escape characters.')
Use triple quotes """..."""
or '''...'''
to construct multi-line strings.
print('''This is
a multi-
line string''')
print("""This is
another multi-
line string""")
Individual characters are accessed by indexing string[idx]
0
from the left, and-1
from the rightFor slices, string[start:end:step]
start
index is inclusive,end
index is exclusive, i.e. the interval is [start,end)
e = "Another example string"
print(e[0])
print(e[-3])
print(e[8:15])
print(e[14:7:-1])
print(e[-14:-6])
There are many string methods available:
.startswith(prefix[, start[, end]]) -> bool
.endswith(suffix[, start[, end]]) -> bool
.find(sub[, start[, end]]) -> int
.lower() -> str
.upper() -> str
.replace(old, new[, count]) -> str
.split(sep=None, maxsplit=-1) -> list of strings
.strip([chars]) -> str
s = 'This is a test string!'
print(s.startswith("This"), s.endswith("string"))
print(s.upper(), s.lower())
print(s.replace("string","list"))
print(s)
Remember strings are immutable and a new* string is always returned when "modifying" a string!*
help
(and dir
)¶dir()
.help()
print(', '.join(s for s in dir(str()) if '__' not in s))
help(str().split)
.split()
¶When parsing text
.split()
methodFor example,
"Blue, Green, Red, Yellow, Black"
text = "Blue, Green, Red, Yellow, Black"
split_text = text.split(sep=', ')
print(split_text)
You can of course use any character to split on. (Also look at rsplit()
)
.format()
¶'1: Hello {}, do you like {} tea?'.format( "John", "green")
'2: Hello {0}, do you like {1} tea? I like {1} tea!'.format( "John", "green")
'3: Hello {1}, do you like {0} tea?'.format( "John", "green")
'4: Hello {0[0]}, do you like {0[1][2]} tea?'.format(["John", ["black", "red", "green"]])
'5: Hello {name}, do you like {color} tea?'.format(color="green", name="John")
print
¶sys.stdout
, but can be re-directed to (other) files as well.print
command:help(print)
print
examples¶print(1, 2, 3, 4, 5, sep=':')
print("First output", end=" | ")
print("Second output")
print
¶There are two basic methods for formatting output in Python
print( "My integer is: %d, my float is %4.3f" % (42, 3.141592653589793) )
.format()
method in Python 3 (recommended)print( "My integer is: {}, my float is {:4.3f}".format(42, 3.141592653589793) )
The format specifier (the part after the : inside the brackets) have this syntax:
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]
fill ::= <any character>
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= integer
precision ::= integer
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
For full information on the str.format formats, see https://docs.python.org/3/library/string.html#format-string-syntax
See also the nice focused guide with examples: https://pyformat.info/
Python 3.6 introduced a shorter means of formatting output:
a = 3
b = 2.5
print(f"a is equal to {a} and b is equal to {b}")
Here the "f" before the initial quote marks it as a format string.
sys.stdout
and sys.stdin
sys.stdout
and sys.stdin
are available automatically (no explicit open needed)open()
function:file = open(filename, mode)
mode
s are"r"
for reading from a file,"w"
for writing to a file and"a"
to append to an existing fileclose()
methodhelp(open)
for detailshelp(open)
text = """Hear hear!
This string will be saved to file for all eternity.
To read or not to read that is the question."""
with open('test_file.txt', mode='w') as file:
file.write(text)
with open('test_file.txt', mode='r') as file:
new_text = file.read()
print(new_text)
with
instead of file.close()
¶file.close()
method is not needed when using the with
statementdel file
at the end of the scopefile.close()
for files)file = open('test_file.txt', mode='r')
print(file.read())
file.close() # I always forget to add this...
with open('test_file.txt', mode='r') as file:
print(file.read())
# Here the file is automagically closed, nothing to forget! :D
.readline()
- reads a full line (from a text file).read(n)
- reads $n$ (or all remaning if $< n$) characters from the fileThe following two examples does exactly the same thing:
with open('test_file.txt', 'r') as file:
line = file.readline()
while line:
print(line)
line = file.readline()
with open('test_file.txt', 'r') as file:
for line in file:
print(line)
Note that: While the input-file had no empty lines, there are empty lines in the output.
\n
andprint
adds a linebreak by default, i.e.print(text)
is equal to print(text, end='\n')
To avoid this
strip()
or rstrip()
string methodsend=''
with open('test_file.txt', 'r') as file:
for line in file:
print(line.rstrip())
with open('test_file.txt', 'r') as file:
for line in file:
print(line, end='')
.read()
and .readlines()
¶.read()
method reads the entire file, whilereadlines()
method reads the entire file in to a list of strings.write()
¶.write()
methodwith open('test_file_2.txt', mode='w') as file:
file.write('Hello .write() world!\n')
file.write('Bye bye!\n')
with open('test_file_2.txt', mode='r') as file:
for line in file:
print(line, end='')
print
¶.write()
is print()
print()
can be redirected from sys.stdout
to a filewith open('test_file_2.txt', mode='w') as file:
print('Hello print() world!', file=file)
print('Bye bye!', file=file)
with open('test_file_2.txt', mode='r') as file: print(file.read())
numpy
andnumpy.linalg
import numpy as np
print(dir(np))
print(dir(np.linalg))
That the sub-module structure corresponds to folders we can see by
.__file__
, orprint(np.linalg.__file__)
help
function is usefulhelp(np.zeros)
is the fundamental package for scientific computing with Python.
It contains among other things:
(source https://numpy.org/)
Documentation:
list
¶list
)list
type keeps references to objects instead of the data itselflist
very flexible, but it also givesndarray
¶ndarray
in NumPy, on the other hand,Quite a few other external libraries (like SciPy) expects data in NumPy format
to give good performace, or to work at all!
list
: Element-wise operations¶list
a = [1, 3, 4]
b = [3, 2, 5]
c = a * b + 1 # Multiply each element and add 1, Does _not_ work!
c = []
for A, B in zip(a, b):
C = A * B + 1
c.append(C)
print(c)
ndarray
: Element-wise operations¶ndarray
support elementwise operations (similar to Matlab)import numpy as np
a = np.array([1, 3, 4])
b = np.array([3, 2, 5])
print(type(a), type(b))
c = a * b + 1 # Multiply each element in a and b and add 1
print(c)
ndarray
type and element dtypes
¶ndarray
is the most prominent NumPy data-typendarray
stands for N-Dimensional Arraydtype
argument)dtypes
includeint8
, int16
, int32
, int64
,int == int64 or int32
depending on your platform)uint8
, uint16
, uint32
, uint64
float16
, float32
, float64
, (float == float64
)complex64
, complex128
, (complex == complex128
)float
by defaultimport numpy as np
a = np.array([1, 3, 4])
b = np.array([3, 2, 5], dtype=np.int8)
c = a * b + 1
print(c)
print(type(c))
print(type(c[0]))
print(c.dtype)
In the example above, we created a NumPy array from a Python list.
This is one way of creating a NumPy array, more will be shown later.
shape
of an ndarray
¶ndarray
can have any number of dimensionsshape
of the arrayshape
of an array is a tuple
a = np.array([
[1., 3.],
[2., 7.],
[.4, 6.],
])
a.shape
print(a)
tuple
np.zeros()
, np.ones()
, and np.empty()
shape = (2, 4)
a = np.zeros(shape, dtype=int)
b = np.ones(shape, dtype=complex)
c = np.empty(shape, dtype=float)
print(a)
print(b)
print(c)
Note: np.empty
gives non-initialized arrays (fast), but they have an undefined inital value.
np.arange
¶np.arange(start=0, stop, step=1)
start
is inclusive, stop
is exclusiveint
and float
a = np.arange(3)
b = np.arange(stop=10, start=24, step=-2)
f = np.arange(1., 3., 0.2)
print("a =", a)
print("b =", b)
print("f =", f)
np.linspace(start, stop, num=10)
c = np.linspace(-1., 1., num=9)
print("c =", c)
The best way to learn a new language (computer or other) is of course to use it!
In the Computer Assignments you will have plenty of opportunity to practice, please try to do as much as possible in your group.
In CA1 you will be able to show your skills in:
Lecture contents
The computer assignments should be performed in groups of two.
Please, form groups on your own, whenever possible.
Read through the "General instructions for the computer asignments" and
the entire CA1 description (all the three steps) before starting to code.
Deadline for CA1 is Sunday 9/2, 2020! (actually 07.00h Monday moorning)
import antigravity