Sei sulla pagina 1di 27

Python Crash Course

strings, math
Bachelors
V1.0
dd 12-12-2014
Hour 6

Introduction to language - strings


>>> 'spam and eggs'
'spam and eggs'
>>> 'doesn\'t'
"doesn't"
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said'
>>> hello = 'Greetings!'
>>> hello
'Greetings!'
>>> print(hello)
Greetings!
>>> print(hello + ' How do you do?')
Greetings! How do you do?
>>> print(hello, 'How do you do?')
Greetings! How do you do?
>>> howdo = 'How do you do?'
>>> print(hello+' '+howdo)
Greetings! How do you do?

>>> s = "GMRT is a telescope!" # Assignment


>>> len(s) # Length; no trailing NULL
>>> "gmrt" + "gmrt" # Concatination
>>> 'gmrt' + "gmrt"
>>> 'gmrt' + 100 # No automatic conversion,
wont work
>>> 'gmrt' + 100
>>> 'gmrt' * 100
>>> 'gmrt' * 100

>>>
>>>
>>>
>>>
>>>

s = "GMRT is a radio telescope!"


s[0] # First character
s[1] # Second character
s[100] # Bounds are checked!
s[-1] # ?

Introduction to language - strings

triple-quotes (docstrings)

In [12]: usage = """


....: Usage: thingy [OPTIONS]
....:
-h
....:
-H hostname
....: """
In [14]: usage
Out[15]: '\nUsage: thingy [OPTIONS]\n
message\n
-H hostname

Display this usage message


Hostname to connect to

-h
Hostname to connect to\n'

In [15]: print usage


Usage: thingy [OPTIONS]
-h
-H hostname

Display this usage message


Hostname to connect to

Display this usage

Introduction to language - strings

raw string

In [1]: hello = r"This is a rather long string containing\n\


...: several lines of text much as you would do in C."
In [2]:
In [2]: print hello
This is a rather long string containing\n\
several lines of text much as you would do in C.
>>> hello = "asdasd\
... adasda"
>>> print hello
asdasdadasda
>>>

Introduction to language - slicing


>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>

s = "GMRT is a radio telescope!"


s[2:5]
# Includes s[2], but not s[5]
s[5:2]
# Empty string
s[2:2]
# again empty
s[5:-1]
# Excludes last character
s[-100:100]
# Bounds are ignored here
s[:5]
# Default first index: 0
s[5:]
# Default last index: len(s)
s[:]
# Copy of complete string
s[2:10:2]
s[::-1]

>>> s = "GMRT works great!"


>>> s[5] = "F"
>>> s = s[:5] + "F" + s[6:]

# Strings are immutable!

>>> s.replace("great", "poorly")


>>> print s
# s is unchanged!
>>> s = s.replace("great", "poorly")

Object oriented programming


creeping in:
>>>
>>>
>>>
>>>
>>>
>>>

" Hello world ".strip()


s = "GMRT is in Khodad!"
s.split() # List of strings
s = "GMRT\tis\nin Khodad!"
s.split()
s.split("o")

String Methods
SN
1
2
3

6
7

Methods with Description


capitalize()
Capitalizes first letter of string
center(width, fillchar)
Returns a space-padded string with the original string
centered to a total of width columns
count(str, beg= 0,end=len(string))
Counts how many times str occurs in string, or in a
substring of string if starting index beg and ending
index end are given
decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for
encoding. encoding defaults to the default string
encoding.
encode(encoding='UTF-8',errors='strict')
Returns encoded string version of string; on error,
default is to raise a ValueError unless errors is given
with 'ignore' or 'replace'.
endswith(suffix, beg=0, end=len(string))
Determines if string or a substring of string (if starting
index beg and ending index end are given) ends with
suffix; Returns true if so, and false otherwise
expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to
8 spaces per tab if tabsize not provided
find(str, beg=0 end=len(string))
Determine if str occurs in string, or in a substring of
string if starting index beg and ending index end are
given; returns index if found and -1 otherwise
index(str, beg=0, end=len(string))
Same as find(), but raises an exception if str not found

SN Methods with Description


9 isa1num()
Returns true if string has at least 1 character and all
characters are alphanumeric and false otherwise
10 isalpha()
Returns true if string has at least 1 character and all
characters are alphabetic and false otherwise
11 isdigit()
Returns true if string contains only digits and false
otherwise
12 islower()
Returns true if string has at least 1 cased character
and all cased characters are in lowercase and false
otherwise
13 isnumeric()
Returns true if a unicode string contains only
numeric characters and false otherwise
14 isspace()
Returns true if string contains only whitespace
characters and false otherwise
15 istitle()
Returns true if string is properly "titlecased" and
false otherwise
16 isupper()
Returns true if string has at least one cased
character and all cased characters are in uppercase
and false otherwise
17 join(seq)
Merges (concatenates) the string representations of
elements in sequence seq into a string, with
separator string
18 len(string)
Returns the length of the string

String Methods
SN Methods with Description
19 ljust(width[, fillchar])
Returns a space-padded string with the original
string left-justified to a total of width columns
20 lower()
Converts all uppercase letters in string to lowercase
21 lstrip()
Removes all leading whitespace in string
22 maketrans()
Returns a translation table to be used in translate
function.
23 max(str)
Returns the max alphabetical character from the
string str
24 min(str)
Returns the min alphabetical character from the
string str
25 replace(old, new [, max])
Replaces all occurrences of old in string with new, or
at most max occurrences if max given
26 rfind(str, beg=0,end=len(string))
Same as find(), but search backwards in string
27 rindex( str, beg=0, end=len(string))
Same as index(), but search backwards in string
28 rjust(width,[, fillchar])
Returns a space-padded string with the original
string right-justified to a total of width columns.
29 rstrip()
Removes all trailing whitespace of string
30 split(str="", num=string.count(str))
Splits string according to delimiter str (space if not
provided) and returns list of substrings; split into at
most num substrings if given

SN Methods with Description


31 splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and returns a
list of each line with NEWLINEs removed
32 startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if
starting index beg and ending index end are given)
starts with substring str; Returns true if so, and false
otherwise
33 strip([chars])
Performs both lstrip() and rstrip() on string
34 swapcase()
Inverts case for all letters in string
35 title()
Returns "titlecased" version of string, that is, all
words begin with uppercase, and the rest are
lowercase
36 translate(table, deletechars="")
Translates string according to translation table
str(256 chars), removing those in the del string
37 upper()
Converts lowercase letters in string to uppercase
38 zfill (width)
Returns original string leftpadded with zeros to a
total of width characters; intended for numbers,
zfill() retains any sign given (less one zero)
39 isdecimal()
Returns true if a unicode string contains only decimal
characters and false otherwise

Escape characters
Backslash
notation

Hexadecimal
character

Description

\a

0x07

Bell or alert

\b

0x08

Backspace

\cx

Control-x

\C-x

Control-x

\e

0x1b

Escape

\f

0x0c

Formfeed

\M-\C-x
\n

Meta-Control-x
0x0a

\nnn

Newline
Octal notation, where n is in the range 0.7

\r

0x0d

Carriage return

\s

0x20

Space

\t

0x09

Tab

\v

0x0b

Vertical tab

\x

Character x

\xnn

Hexadecimal notation, where n is in the range


0.9, a.f, or A.F

String formatting

One of Python's coolest features is the string format operator %.


print "My name is %s and height is %d cm!" % ('Erik', 178)

Symbol

Conversion

Symbol Functionality

%c

character

argument specifies width or precision

%s

string conversion via str() prior to formatting

left justification

%i

signed decimal integer

display the sign

%d

signed decimal integer

<sp>

leave a blank space before a positive number

%u

unsigned decimal integer

%o

octal integer

%x

hexadecimal integer (lowercase letters)

add the octal leading zero ( '0' ) or hexadecimal


leading '0x' or '0X', depending on whether 'x' or
'X' were used.

%X

hexadecimal integer (UPPERcase letters)

pad from left with zeros (instead of spaces)

%e

exponential notation (with lowercase 'e')

'%%' leaves you with a single literal '%'

%E

exponential notation (with UPPERcase 'E')

(var)

mapping variable (dictionary arguments)

%f

floating point real number

m.n.

%g

the shorter of %f and %e

m is the minimum total width and n is the


number of digits to display after the decimal
point (if appl.)

%G

the shorter of %f and %E

str.format()

string module formatting

>>> "Name: {0}, age: {1}".format('John', 35)


'Name: John, age: 35'
>>> tu = (12,45,22222,103,6)
>>> print '{0} {2} {1} {2} {3} {2} {4} {2}'.format(*tu)
12 22222 45 22222 103 22222 6 22222
>>> d = {'web': 'user', 'page': 42}
>>> 'http://xxx.yyy.zzz/{web}/{page}.html'.format(**d)
'http://xxx.yyy.zzz/user/42.html

format() being a function, it can be used as argument in other functions:

>>> li = [12,45,78,784,2,69,1254,4785,984]
>>> print map('the number is {}'.format,li)
['the number is 12', 'the number is 45', 'the number is 78', 'the number is 784', 'the
number is 2', 'the number is 69', 'the number is 1254', 'the number is 4785', 'the
number is 984']

Unicode strings

Unicode has the advantage of providing one ordinal for every


character in every script used in modern and ancient texts.
Previously, there were only 256 possible ordinals for script
characters.
In [22]: u'Hi'
Out[22]: u'Hi'
In [23]: u'H'
Out[23]: u'H\ufffd
In [24]: s = u'H'
In [25]: str(s)
--------------------------------------------------------------------------UnicodeEncodeError
Traceback (most recent call last)
<ipython-input-28-d22ffcdd2ee9> in <module>()
----> 1 str(s)
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 1:
ordinal not in range(128)
In [26]: u'H'.encode('utf-8')
Out[26]: 'H\xef\xbf\xbd'

Converting strings and numbers


>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>

# Numbers to strings:
str(123), str(2**1000)
str(1.e10), str(1.+2j)
# Strings to numbers:
int("123"), int("1234567890"*100)
float("1.23"), float("1.23e10")
float("1.23 e10") # Error
"123".isdigit()
"1.23".isdigit() # :-(

very similar to sprintf in C


>>> import math
>>> s = "%s is %10.3g" % ("Pi", math.pi)
>>> print s

Riddle: what would the following produce?


>>> var1 = 'hello'
>>> 'o'.join((var1.title().swapcase().split('E')))[0:-1] + 'w'

Introduction to language math


Functions:
>>>
>>>
>>>
>>>
>>>
>>>

abs(-2.)
abs(1+1j)
max(1,2,3,4)
min(1,2,3,4)
hex(17), oct(-5)
round(1.23456, 2) # negative precision allowed

Comparisons:
>>> 5 * 2 == 4 + 6
True
>>> 0.12 * 2 == 0.1 + 0.14
False
>>> a = 0.12 * 2; b = 0.1 + 0.14
>>> eps = 0.0001
>>> a - eps < b < a + eps
True

Mathematical and Trigonometric Functions


Function

Returns ( description )

abs(x)

The absolute value of x: the (positive) distance


between x and zero.

ceil(x)

Function

Description

acos(x)

Return the arc cosine of x, in radians.

asin(x)

Return the arc sine of x, in radians.

cmp(x, y)

The ceiling of x: the smallest integer not less


than x
-1 if x < y, 0 if x == y, or 1 if x > y

atan(x)

Return the arc tangent of x, in radians.

exp(x)

The exponential of x: ex

atan2(y, x)

Return atan(y / x), in radians.

fabs(x)

The absolute value of x.

floor(x)

cos(x)

Return the cosine of x radians.

hypot(x, y)

log(x)

The floor of x: the largest integer not greater


than x
The natural logarithm of x, for x> 0

Return the Euclidean norm, sqrt(x*x +


y*y).

log10(x)

The base-10 logarithm of x for x> 0 .

sin(x)

Return the sine of x radians.

tan(x)

Return the tangent of x radians.

degrees(x)

Converts angle x from radians to


degrees.

radians(x)

Converts angle x from degrees to


radians.

max(x1, x2,.. The largest of its arguments: the value closest


.)
to positive infinity
min(x1, x2,... The smallest of its arguments: the value
)
closest to negative infinity
modf(x)

The fractional and integer parts of x in a twoitem tuple. Both parts have the same sign as x.
The integer part is returned as a float.

pow(x, y)

The value of x**y.

round(x [,n]) x rounded to n digits from the decimal point.


Python rounds away from zero as a tiebreaker: round(0.5) is 1.0 and round(-0.5) is
-1.0.
sqrt(x)
The square root of x for x > 0

Comparson operators
Assume variable a holds 10 and variable b holds 20 then:
Operator Description

Example

==

Checks if the value of two operands are


equal or not, if yes then condition
becomes true.
Checks if the value of two operands are
equal or not, if values are not equal then
condition becomes true.

(a == b) is not true.

<>

Checks if the value of two operands are


equal or not, if values are not equal then
condition becomes true.

(a <> b) is true. This is similar to !=


operator.

>

Checks if the value of left operand is


(a > b) is not true.
greater than the value of right operand, if
yes then condition becomes true.

<

Checks if the value of left operand is less


than the value of right operand, if yes
then condition becomes true.

>=

Checks if the value of left operand is


(a >= b) is not true.
greater than or equal to the value of right
operand, if yes then condition becomes
true.
Checks if the value of left operand is less (a <= b) is true.
than or equal to the value of right
operand, if yes then condition becomes
true.

!=

<=

(a != b) is true.

(a < b) is true.

Bitwise Operators
Bitwise operator works on
bits and perform bit by bit
operation.

There are following Bitwise operators supported by Python language


Operator Description

Example

Assume if a = 60; and b =


13; Now in binary format
they will be as follows:

&

Binary AND Operator copies a bit to the


result if it exists in both operands.

(a & b) will give 12 which is


0000 1100

Binary OR Operator copies a bit if it exists (a | b) will give 61 which is


in eather operand.
0011 1101

Binary XOR Operator copies the bit if it is (a ^ b) will give 49 which is


set in one operand but not both.
0011 0001

Binary Ones Complement Operator is


unary and has the efect of 'flipping' bits.

(~a ) will give -60 which is


1100 0011

<<

Binary Left Shift Operator. The left


operands value is moved left by the
number of bits specified by the right
operand.

a << 2 will give 240 which is


1111 0000

>>

Binary Right Shift Operator. The left


operands value is moved right by the
number of bits specified by the right
operand.

a >> 2 will give 15 which is


0000 1111

a = 0011 1100
b = 0000 1101
----------------a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

Logical Operators
How logical operators work in Python:
Operator

Description

Example a,b = 10,02 Example a,b = 0,02

and

Called Logical AND operator. If


(a and b) is true.
both the operands are true then
then condition becomes true.

(a and b) is false.

or

Called Logical OR Operator. If


(a or b) is true.
any of the two operands are non
zero then then condition
becomes true.

(a or b) is true.

not

Called Logical NOT Operator. Use not(a and b) is false. not(a and b) is true.
to reverses the logical state of
its operand. If a condition is true
then Logical NOT operator will
make false.

Number formatting
>>> print "Today's stock price: %f" % 50.4625
50.462500
>>> print "Today's stock price: %.2f" % 50.4625
50.46
>>> print "Change since yesterday: %+.2f" % 1.5
+1.50

>>> "Name: %s, age: %d" % ('John', 35)


'Name: John, age: 35'
>>> i = 45
>>> 'dec: %d/oct: %#o/hex: %#X' % (i, i, i)
'dec: 45/oct: 055/hex: 0X2D'
>>> "MM/DD/YY = %02d/%02d/%02d" % (12, 7, 41)
'MM/DD/YY = 12/07/41'
>>> 'Total with tax: $%.2f' % (13.00 * 1.0825)
'Total with tax: $14.07'
>>> d = {'web': 'user', 'page': 42}
>>> 'http://xxx.yyy.zzz/%(web)s/%(page)d.html' % d
'http://xxx.yyy.zzz/user/42.html'

Accuracy
Our society depends on software. This may be an obvious statement.
Software bugs cost the U.S. economy 60 billion dollars each year. It is
stated that a third of that cost could be eliminated by improved testing.
Bugs can cause accidents, also in science, although in astronomy
people usually do not end up in a hospital.
In this lecture we focus on floating point numbers. It is important to
realize that these numbers are represented by a limited number of bits
and therefore are limited to a certain precision. We discuss two sources
of error:
Rounding,
and
Cancellation.

Real life examples


Software causing severe problems
Patriot missile. Time conversion of integer to float with error
therefor missing target. Tested only for < 100 hours.
Truncation of amounts in stock market transactions and currency
conversions.
Exploding Ariane 5 rocket in 1996 due to limited size of integer
memory storage.
Illegal input not handled correctly: USS Yorktown three hours no
propulsion due to database overflow.

Internal representation

Calculations use a fixed number of significant digits. After each


operation the result usually has to be rounded. The error is less than
(or equal) half a unit represented by the last bit of the internal
representation. In loops these errors can propagate and grow.

>>> 0.1+0.2
0.30000000000000004
>>> from decimal import Decimal
>>> Decimal(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal (0.2)
Decimal('0.200000000000000011102230246251565404236316680908203125')
>>> Decimal (0.1+0.2)
Decimal('0.3000000000000000444089209850062616169452667236328125')

Rounding

Calculations use a fixed number of significant digits. After each


operation the result usually has to be rounded. The error is less than
(or equal) half a unit represented by the last bit of the internal
representation. In loops these errors can propagate and grow.
def step( a, b, n ):
""" Function to calculate intermediate steps in an interval """
h = (b-a) / n
x = a
print "%.18f" % (x)
while (x < b):
x = x + h
print "%.18f" % (x)
step (1.0, 2.0, 3)
1.000000000000000000
1.333333333333333259
1.666666666666666519
1.999999999999999778
2.333333333333333037

Rounding
Enhancing the accuracy
Replacing the condition in the while statement with a better one.
def step( a, b, n ):
""" Function to calculate intermediate steps in an interval """
eps = 1.0e-8
h = (b-a) / n
x = a
print "%.18f" % (x)
while (abs(x b) > eps):
x = x + h
print "%.18f" % (x)
step(1.0, 2.0, 3)
1.000000000000000000
1.333333333333333259
1.666666666666666519
1.999999999999999778

Rounding
Enhancing the accuracy
Replacing the while with a for loop using an integer.
def step( a, b, n ):
""" Function to calculate intermediate steps in an interval """
eps = 1.0e-8
h = (b-a) / n
x = a
print "%.18f" % (x)
for i in range(0,n+1):
x = x + h
print "%.18f" % (x)
step(1.0, 2.0, 3)
1.000000000000000000
1.333333333333333259
1.666666666666666519
1.999999999999999778

Cancellation
Cancellation occurs from the subtraction of two almost equal numbers. If
you subtract two numbers with approximate equal values then the errors are
also comparable and in the subtraction we get a small value with a relatively
big error (which can be demonstrated with simple error analysis). This effect
is demonstrated when you try to calculate the roots of the equation:
This equation has two analytical expressions for finding the roots:

With a=1.0e-5, b = 1.0e3 and c = 1.0e3

Cancellation
Consider the following code
import math
a=1.0e-5; b = 1.0e3; c = 1.0e3
sq = math.sqrt(b*b-4.0*a*c)
xa1 = (-b + sq)/(2.0*a)
xa2 = (-b - sq)/(2.0*a)
print "\nx1,x2: ", xa1,xa2
print "We expect: x1*x2-c/a=0, but result is:", xa1*xa2-c/a
print "x1 from c/(a*x2)=", c/(a*xa2)
xb1 = (-2.0*c) / (b + sq)
xb2 = (-2.0*c) / (b - sq)
print "\nx1,x2: ", xb1,xb2
print "We expect x1*x2-c/a=0, but result is:", xb1*xb2-c/a
print "x2 from c/(a*x1)", c/(a*xb1)
print "\nsqrt should be 999.99998, and result is: %12f "% sq
x1,x2: -1.00000001 -99999999.1156
We expect x1*x2-c/a=0, but result is: 0.115607380867
x2 from c/(a*x1) -99999999.0
sqrt should be 999.99998, and result is:
999.999980

Logical Operators

End

Potrebbero piacerti anche