Programming tricks: tidbits of Python

Strings: continuation lines, with a backslash can used; \n need to be included explicitly; spaces at the beginning of the next line are significant.

hello = "String continuing\
on and on\
and on and on…"
print hello

In a raw string ("quotes" prefixed by "r"), escapes are not escape, continuation is honored but printed, newline is allowed.

hello2 = r"String continuing\
on and on"
print hello2

Triple quotes will allow end of lines.

hello3 = «"String going to the
next line»"
print hello3

Slice notation: first number is beginning character, second number is ending character, not included; [:n] goes from beginning, [n:] goes to end, [:] gets all AND FORCES COPY negative indices are counted from the end; degenerate slices are handled gracefully.

mystr = 'alpha'
print mystr[0],mystr[4],mystr[:2]

Strings are immutable! Can't assign to slices… But LISTS are mutable.

mylist = ['a','b','c']
mylist[0] = 'A'
print mylist

Removing items, adding items…

mylist[0:1] = []
print mylist
mylist[:0] = ['t']
print mylist
mylist[4:5] = ['y']


mylist = mylist + ['y']
print mylist

The length function is len(str).

print len(mylist)

Control statements: iterate over list

for i in mylist:
	print i

iterate over indices of a sequence

for i in range(len(mylist)):
	print i, mylist[i]

range(n) generates list of n values starting from 0

print range(5)

for and while can have break, continue.

  • pass" can be used where semantics require a statement, but none is needed

A string literal at the beginning of a function is its "docstring".

Global values are accessible from functions, but they cannot be assigned a value.

The value of a function name can be assigned to another name, that can then be used as a function.

Functions that do not return a value return "None".

The "in" keyword tests whether a sequence contains a value.

Functions can have default parameter value, which if mutable provide a method to implement static variables; can also use the keyword call notation "**name" will receive a dictionary with keyword arguments whose keyword does not correspond to a formal parameter; "*name" will receive a tuple containing the positional arguments beyond the formal parameter list; the "*args" notation can also be used to specify arbitrary number of arguments, or to unpack parameter lists when calling functions.

lambda forms "lambda a, b: a+b" are just syntactic sugar for a function definition.

Feb 15, 2005

pythontidbits (/progtricks)
2005-02-15, 15:03 [edit]

  Login:   Password:   [rss] [cc] [w3] [css]

© M. Vallisneri 2012 — last modified on 2010/01/29

Tantum in modicis, quantum in maximis