prev | Draft Version 546 (Thu Dec 1 09:18:30 2005) | next |
if
, elif
, and else
)while
loops (with break
and continue
)str = 'abc' print 'str is', str str[0] = 'x' print 'str is now', str
str is abc
Traceback (most recent call last): File "immutable_err.py", line 3, in ? str[0] = 'x' TypeError: object does not support item assignment
str = 'abc' print 'str is', str str = 'xyz' print 'str is now', str
str is abc str is now xyz
text[0]
is the first character of the string text
len
returns the length of a string…text
is len(text)-1
element = "boron" i = 0 while i < len(element): print element[i] i += 1
b o r o n
text[start:end]
takes a slice out of text
text
from start
up to (but not including) end
val = "helium" print val[1:3], val[:2], val[4:]
el he um
text[1:2]
is either the second character in text
, or the empty string (if text
doesn't have a second character)text[1:1]
is always the empty stringtext[2:1]
is always the empty stringx[-1]
is the last characterx[len(x)-1]
x[-2]
is the second-to-last characterval = "carbon" print val[-2], val[-4], val[-6]
o r c
val = "helium" print val[1:22] x = val[22]
elium
Traceback (most recent call last): File "bounds.py", line 3, in ? x = val[22] IndexError: string index out of range
M
of object X
, type X.M()
Method | Purpose | Example | Result |
---|---|---|---|
capitalize | Capitalize first letter of string | "text".capitalize() | "Text" |
lower | Convert all letters to lowercase. | "aBcD".lower() | "abcd" |
upper | Convert all letters to uppercase. | "aBcD".upper() | "ABCD" |
strip | Remove leading and trailing whitespace (blanks, tabs, newlines, etc.) | " a b ".strip() | "a b" |
lstrip | Remove whitespace at left (leading) edge of string. | " a b ".lstrip() | "a b " |
rstrip | Remove whitespace at right (trailing) edge of string. | " a b ".rstrip() | " a b" |
count | Count how many times one string appears in another. | "abracadabra".count("ra") | 2 |
find | Return the index of the first occurrence of one string in another, or -1. | "abracadabra".find("ra") | 2 |
"abracadabra".find("xyz") | -1 | ||
replace | Replace occurrences of one string with another. | "abracadabra".replace("ra", "-") | "ab-cadab-" |
text = "Hogwarts" print text.upper() print text.replace("rts", "sh")
HOGWARTS Hogwash
text = "Hogwarts" print "method result is", text.replace("rts", "sh") print "variable text is", text
method result is Hogwash variable text is Hogwarts
text = "Hermione" print ':' + text.upper()[4:7].center(10) + ':'
: ION :
is
to check whether one string appears in anotherprint "atta" in "gatcattcgat" print "tcga" in "gatcattcgat"
False True
[]
, [3]
, [5, "b"]
x = ["a", 2, "bcd", 4] print x[0] print x[-1] print x[1:-1]
a 4 [2, 'bcd']
x[i] = v
gases = ["helium", "argon", "neon"] print gases i = 0 while i < len(gases): gases[i] = "changed" print gases i += 1
['helium', 'argon', 'neon'] ['changed', 'argon', 'neon'] ['changed', 'changed', 'neon'] ['changed', 'changed', 'changed']
left = ['L', 'E', 'F', 'T'] right = ['W', 'R', 'I', 'T', 'E'] both = left + right print both
['L', 'E', 'F', 'T', 'W', 'R', 'I', 'T', 'E']
list(text)
creates a list whose elements are the characters of the string text
print list("Dumbledore")
['D', 'u', 'm', 'b', 'l', 'e', 'd', 'o', 'r', 'e']
del
deletes something from the list, and shortens the listvalues = ['a', 'b', 'c', 'd', 'e'] print 'original', values del values[2] print 'after deleting item 2', values del values[-2:] print 'after deleting last two remaining items', values
original ['a', 'b', 'c', 'd', 'e'] after deleting item 2 ['a', 'b', 'd', 'e'] after deleting last two remaining items ['a', 'b']
del
modifies the list, and doesn't return anythingx
is initially ['c', 'a', 'b', 'c']
Method | Purpose | Example | Result |
---|---|---|---|
append | Add to the end of the list. | x.append(99) | ['c', 'a', 'b', 'c', 99] |
count | Count how many times something appears in the list. | x.count('c') | 2 |
index | Find the first occurrence of something in the list. | x.index('a') | 1 |
insert | Insert something into the list. | x.insert(2, 'diamond') | ['c', 'a', 'diamond', 'b', 'c'] |
remove | Remove the first occurrence of something from the list. | x.remove('c') | ['a', 'b', 'c'] |
reverse | Reverse the list in place. | x.reverse() | ['c', 'b', 'a', 'c'] |
sort | Sort the list in place. | x.sort() | ['a', 'b', 'c', 'c'] |
list.index
can't find the item it's searching forlist.reverse
and list.sort
change the list, and return None
x = x.reverse()
is a common errorx
, but then sets x
to None
, so all data is lostfor
statement automatically loops over the content of a collectionfor x in text
sets x
to each character of text
in turnfor x in someList
sets x
to each element of someList
in turnfor c in 'lead': print '+' + c + '+', print for x in ['helium', 'argon', 'neon']: print x.capitalize()
+l+ +e+ +a+ +d+ Helium Argon Neon
print
statement suppresses the automatic newlinerange
creates the list [start, start+1, ..., end-1]
end-1
, just as x[start:end]
is the elements of x
up to, but not including, end
range(end)
is the same as range(0, end)
range(start, end, step)
goes in increments of step
print range(2, 5) print range(3) print range(2, 10, 3) print range(3, 1)
[2, 3, 4] [0, 1, 2] [2, 5, 8] []
for i in range(N)
for i in range(len(sequence))
chars = "abc" for i in range(len(chars)): print i, chars[i]
0 a 1 b 2 c
x in c
is True
if the value x
is in the collection c
'x' in 'Harry'
is False
'ar' in 'Harry'
is True
3 in [1, 2, 3, 4]
is True
[2, 3] in [1, 2, 3, 4]
is False
vowels = 'aeiou' for v in vowels: if v in 'uranium': print v
a i u
x = [[13, 17, 19], [23, 29]] print x[1] print x[0][1:3]
[23, 29] [17, 19]
x = [['a', 'b'], ['c', 'd', 'e']] y = x[0] print 'before: nested list is', x print '...and sublist is', y y[0] = 123 print 'after: nested list is', x print '...and sublist is', y
before: nested list is [['a', 'b'], ['c', 'd', 'e']] ...and sublist is ['a', 'b'] after: nested list is [[123, 'b'], ['c', 'd', 'e']] ...and sublist is [123, 'b']
x = [['a', 'b'], ['c', 'd', 'e'], ['f', 'g']] y = x[0:2] print 'before: nested list is', x print '...and slice is', y y[0] = 123 print 'after: nested list is', x print '...and modified slice is', y
before: nested list is [['a', 'b'], ['c', 'd', 'e'], ['f', 'g']] ...and slice is [['a', 'b'], ['c', 'd', 'e']] after: nested list is [['a', 'b'], ['c', 'd', 'e'], ['f', 'g']] ...and modified slice is [123, ['c', 'd', 'e']]
(1, 2, 3)
instead of [1, 2, 3]
()
(55,)
(55)
has to be just the integer 55, or the mathematicians will get upseta, b = 2, 3
assigns 2 to a
, and 3 to b
a, b = (2, 3)
a, b, c = [1, 2, 3]
does what you'd expecta, b = [1, 2, 3, 4]
is an errora, b = b, a
swaps the values in a
and b
for
loops to unpack structures on the flycorners = [[1, 3], [2, 7], [4, 0], [4, 9]] sumX, sumY = 0, 0 for cX, cY in corners: sumX += cX sumY += cY sumX = float(sumX) / len(corners) sumY = float(sumY) / len(corners) print "center is", sumX, sumY
center is 2.75 4.75
open()
to open a file'r'
(for read) or 'w'
for writeinfile = open('file.txt', 'r') outfile = open('copy.txt', 'w') line = infile.readline() while line: outfile.write(line) line = infile.readline() infile.close() outfile.close()
file.txt
for reading, and assigns the file object to input
copy.txt
for writing, and assigns the file object to output
input
line
is assigned the value None
Null
in C, or null
in Java, it means “nothing here”, and is considered falseoutput
input
and output
infile = open('file.txt', 'r') outfile = open('copy.txt', 'w') for line in infile: outfile.write(line) infile.close() outfile.close()
infile = open('file.txt', 'r') contents = infile.readlines() infile.close() outfile = open('copy.txt', 'w') outfile.writelines(contents) outfile.close()
Exercise 7.1:
What does "aaaaa".count("aaa")
return? Why?
Exercise 7.2:
What does the built-in function enumerate
do? Use it to
write a function called findOver
that takes a list of numbers
called values
, and a number called threshold
, as
arguments, and returns a list of the locations where items in
values
are greater than threshold
. For example,
findOver([1.1, 3.8, -1.6, 7.4], 2.0)
should return [1, 3]
,
since the values in the input list at locations 1 and 3 are
greater than the threshold 2.0.
Exercise 7.3:
What do each of the following five code fragments do? Why?
x = ['a', 'b', 'c', 'd'] x[0:2] = [] |
x = ['a', 'b', 'c', 'd'] x[0:2] = ['q'] |
x = ['a', 'b', 'c', 'd'] x[0:2] = 'q' |
x = ['a', 'b', 'c', 'd'] x[0:2] = 99 |
x = ['a', 'b', 'c', 'd'] x[0:2] = [99] |
Exercise 7.4:
What does 'a'.join(['b', 'c', 'd'])
return? If you have
a list of strings, how can you concatenate them in a single statement?
Why do you think join
is written this way, rather than as
['b', 'c', 'd'].join('a')
?
prev | Copyright © 2005, Python Software Foundation. See License for details. | next |