>>> s ='hello'# Make a new variable 's' and make it refer to a string object with value 'hello'
>>> s ="hello"# Same thing, with double-quotes
>>> s ="""hello"""# Same thing, with triple-quotes
>>> s
'hello'# By default Python displays strings with single quotes around them
>>>print(s)
hello # Printing a string does not result in surrounding quotes
Strings can be treated like a sequence of characters:
>>> s ='abcd'
>>> s[2]# Get the character at index 2 (the third character)
'c'
>>>len(s)# Get the length of the string (the number of characters)
4
Strings can be concatenated (glued together) with the + operator, and repeated with *:
hello ='hello'# String literals can use single quotes
world ="world"# or double quotes; it does not matter.
hw = hello +' '+ world # String concatenation
print(hw)# prints "hello world"
print(3*'un'+'ium')# 3 times 'un', followed by 'ium'; prints "unununium"
Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated.
This feature is particularly useful when you want to break long strings.
print('Py''thon')# prints 'Python'
You can get a string representation of most Python objects:
>>> x =123
>>>str(x)
'123'
You can also split and join strings together:
>>> words ='Dog versus cat'.split()# Split a string by whitespace
>>> words
['Dog','versus','cat']# The result is a list of string objects
>>>'-'.join(words)# Make a string object with value '-' and then call its join()
'Dog-versus-cat'
string functions:
s ="hello"
print(s.capitalize())# Capitalize a string; prints "Hello"
print(s.upper())# Convert a string to uppercase; prints "HELLO"
print(s.rjust(7))# Right-justify a string, padding with spaces; prints " hello"
print(s.center(7))# Center a string, padding with spaces; prints " hello "
print(s.replace('l','(ell)'))# Replace all instances of one substring with another;
# prints "he(ell)(ell)o"
print(' world '.strip())# Strip leading and trailing whitespace; prints "world"
The "old style" string formatting in Python is similar to the printf function in C:
>>> name ='Jack'
>>> age =7
>>>'%s is %d years old'%(name, age)
'Jack is 7 years old'
The formatting scheme is similar to the printf function in C, where %s means string, %.2f means "floating point value with 2 decimals of precision," etc.
Numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays.
A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension.
import numpy as np
a = np.array([1,2,3])# Create a rank 1 array
print(type(a))# Prints "<class 'numpy.ndarray'>"
print(a.shape)# Prints "(3,)", means we have 3 elements in the outter array.
print(a[0], a[1], a[2])# Prints "1 2 3"
a[0]=5# Change an element of the array
print(a)# Prints "[5, 2, 3]"
b = np.array([[1,2,3],[4,5,6]])# Create a rank 2 array
print(b.shape)# Prints "(2, 3)", means we have 2 elements in the outter array,
# and 3 elements in the inner array
print(b[0,0], b[0,1], b[1,0])# Prints "1 2 4"
a = np.zeros((2,2))# Create an array of all zeros
print(a)# Prints "[[ 0. 0.]
# [ 0. 0.]]"
b = np.ones((1,2))# Create an array of all ones
print(b)# Prints "[[ 1. 1.]]"
c = np.full((2,2),7)# Create a constant array
print(c)# Prints "[[ 7. 7.]
# [ 7. 7.]]"
d = np.eye(2)# Create a 2x2 identity matrix
print(d)# Prints "[[ 1. 0.]
# [ 0. 1.]]"
e = np.random.random((2,2))# Create an array filled with random values
Every numpy array is a grid of elements of the same type. Numpy tries to guess a datatype when you create an array, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype.
import numpy as np
x = np.array([1,2])# Let numpy choose the datatype
print(x.dtype)# Prints "int64"
x = np.array([1.0,2.0])# Let numpy choose the datatype
print(x.dtype)# Prints "float64"
x = np.array([1,2], dtype=np.int64)# Force a particular datatype
Note: * is elementwise multiplication, not matrix multiplication. We instead use the dot function to compute inner products of vectors, to multiply a vector by a matrix, and to multiply matrices.
import numpy as np
x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])
v = np.array([9,10])
w = np.array([11,12])
# Inner product of vectors; both produce 219
print(v.dot(w))
print(np.dot(v, w))
# Matrix / vector product; both produce the rank 1 array [29 67]
print(x.dot(v))
print(np.dot(x, v))
# Matrix / matrix product; both produce the rank 2 array
The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is “broadcast” across the larger array so that they have compatible shapes.
>>> a = np.array([1.0,2.0,3.0])
>>> b = np.array([2.0,2.0,2.0])
>>> a * b
array([2.,4.,6.])
>>> y = np.array([[10,20,30]])# Create an ndarray with shape (1,3)
>>> x = np.eye(3, dtype=y.dtype)# Create an ndarray with shape (3,3)
>>> x + y # Broadcast y across the rows of x
array([[11,20,30],# = [[1 0 0] + [[10 20 30]]
[10,21,30],# [0 1 0]
[10,20,31]])# [0 0 1]]
>>> x + y.T # Broadcast y.T across the columns of x