prev | Version 1107 (Mon Nov 27 20:45:59 2006) | next |
str[1:-1]
meanstext[0]
is the first character of text
len
returns the length of a stringtext
has index len(text)-1
element = "boron" i = 0 while i < len(element): print element[i] i += 1
b o r o n
$ python
>>> element = 'gold' >>> print 'element is', elementelement is gold
>>> element[0] = 's'TypeError: object does not support item assignment
element = 'gold' print 'element is', element element = 'lead' print 'element is now', element
element is gold element is now lead
text[start:end]
takes a slice out of text
text
from start
up to (but not including) end
element = "helium" print element[1:3], element[:2], element[4:]
el he um
Figure 8.1: Visualizing Indices
$ python
>>> element = 'helium' >>> print element[1:22]elium
>>> x = element[22]IndexError: string index out of range
x[-1]
is the last characterx[-2]
is the second-to-last characterelement = "carbon" print element[-2], element[-4], element[-6]
o r c
x[len(x)-1]
Figure 8.2: Visualizing Negative Indices
text[1:2]
is either:text
…text
doesn't have a second character)text[2:1]
is always the empty stringtext[1:1]
text[1:-1]
is everything except the first and last charactersmeth
of object obj
, type obj.meth()
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-" |
Table 8.1: String Methods |
element = 'helium' print element.upper() print element.replace('el', 'afn') print 'element after calls:', element
HELIUM hafnium element after calls: helium
element = "cesium" print ':' + element.upper()[4:7].center(10) + ':'
: UM :
in
to check whether one string appears in anotherfind
methodprint "ant" in "tantalum" print "mat" in "tantalum"
True False
[]
gases = ['He', 'Ne', 'Ar', 'Kr'] print gases print gases[0], gases[-1]
['He', 'Ne', 'Ar', 'Kr'] He Kr
x[i] = v
gases = ['He', 'Ne', 'Ar', 'Kr'] print 'before:', gases gases[0] = 'H' gases[-1] = 'Xe' print 'after:', gases
before: ['He', 'Ne', 'Ar', 'Kr'] after: ['H', 'Ne', 'Ar', 'Xe']
$ python
>>> gases = ['He', 'Ne', 'Ar', 'Kr'] >>> print 'before:', gasesbefore: ['He', 'Ne', 'Ar', 'Kr']
>>> gases[10] = 'Ra'IndexError: list assignment index out of range
append
to add an element to the end of a listcharacters = [] print characters for c in 'aeiou': characters.append(c) print characters
[] ['a'] ['a', 'e'] ['a', 'e', 'i'] ['a', 'e', 'i', 'o'] ['a', 'e', 'i', 'o', 'u']
element = 'carbon' mass = '14' print element + '-' + mass lanthanides = ['Ce', 'Pr', 'Nd'] actinides = ['Th', 'Pa', 'U'] all = lanthanides + actinides print all
carbon-14 ['Ce', 'Pr', 'Nd', 'Th', 'Pa', 'U']
list(text)
creates a list whose elements are the characters of the string text
water = 'H2O' print 'before conversion:', water water = list(water) print 'after conversion:', water
before conversion: H2O after conversion: ['H', '2', 'O']
del
deletes a list elementorganics = ['H', 'C', 'O', 'N'] print 'original:', organics del organics[2] print 'after deleting item 2:', organics del organics[-2:] print 'after deleting the last two remaining items:', organics
original: ['H', 'C', 'O', 'N'] after deleting item 2: ['H', 'C', 'N'] after deleting the last two remaining items: ['H']
organics = ['H', 'C', 'O', 'N'] print 'original:', organics del organics[1:-1] print 'after deleting the middle:', organics
original: ['H', 'C', 'O', 'N'] after deleting the middle: ['H', 'N']
del
is a statement, not an operatormetals
is initially ['gold', 'iron', 'lead', 'gold']
Method | Purpose | Example | Result |
---|---|---|---|
append | Add to the end of the list. | metals.append('tin') | ['gold', 'iron', 'lead', 'gold', 'tin'] |
count | Count how many times something appears in the list. | metals.count('gold') | 2 |
find | Find the first occurrence of something in the list. | metals.find('iron') | 1 |
metals.find('sulfur') | -1 | ||
insert | Insert something into the list. | metals.insert(2, 'silver') | ['gold', 'iron', 'silver', 'lead', 'gold'] |
remove | Remove the first occurrence of something from the list. | metals.remove('gold') | ['iron', 'lead', 'gold'] |
reverse | Reverse the list in place. | metals.reverse() | ['gold', 'lead', 'iron', 'gold'] |
sort | Sort the list in place. | metals.sort() | ['gold', 'gold', 'iron', 'lead'] |
Table 8.2: List Methods |
index
reports an error if the item can't be foundreverse
and sort
change the list, and return None
False
x = x.reverse()
is a common errorx
, but then sets x
to None
, so all data is lostfor
loops over the content of a collection (such as a string or list)for c in some_string
assigns c
each character of some_string
for v in some_list
assigns v
each value of some_list
for c in 'lead': print '/' + c + '/', print for v in ['he', 'ar', 'ne', 'kr']: print v.capitalize()
/l/ /e/ /a/ /d/ He Ar Ne Kr
range
creates the list [start, start+1, ..., end-1]
end-1
to be consistent with x[start:end]
print 'up to 5:', range(5) print '2 to 5:', range(2, 5) print '2 to 10 by 2:', range(2, 10, 2) print '10 to 2:', range(10, 2) print '10 to 2 by -2:', range(10, 2, -2)
up to 5: [0, 1, 2, 3, 4] 2 to 5: [2, 3, 4] 2 to 10 by 2: [2, 4, 6, 8] 10 to 2: [] 10 to 2 by -2: [10, 8, 6, 4]
range(end)
and range(start, end, step)
range
may generate an empty listfor i in range(N)
for i in range(len(sequence))
element = 'sulfur' for i in range(len(element)): print i, element[i]
0 s 1 u 2 l 3 f 4 u 5 r
x in c
works element-by-element on lists3 in [1, 2, 3, 4]
is True
[2, 3] in [1, 2, 3, 4]
is False
Figure 8.3: Line Segment
elements = [['H', 'Li', 'Na'], ['F', 'Cl']] print 'first item in outer list:', elements[0] print 'second item of second sublist:', elements[1][1]
first item in outer list: ['H', 'Li', 'Na'] second item of second sublist: Cl
elements = [['H', 'Li'], ['F', 'Cl']] gases = elements[1] print 'before' print 'elements:', elements print 'gases:', gases gases[1] = 'Br' print 'after' print 'elements:', elements
before elements: [['H', 'Li'], ['F', 'Cl']] gases: ['F', 'Cl'] after elements: [['H', 'Li'], ['F', 'Br']]
Figure 8.4: Aliasing In Action
metals = ['Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn'] middle = metals[2:-2] print 'before' print 'metals:', metals print 'middle:', middle middle[0] = 'Al' del middle[1] print 'after' print 'metals:', metals print 'middle:', middle
before metals: ['Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn'] middle: ['Fe', 'Co', 'Ni'] after metals: ['Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn'] middle: ['Al', 'Ni']
Figure 8.5: Slicing Lists
(1, 2, 3)
instead of [1, 2, 3]
()
(55,)
(55)
has to be just the integer 55, or the mathematicians will get upset1, 2, 3
is the same as (1, 2, 3)
left, right = "gold", "lead"
assigns "gold"
to left
, and "lead"
to right
left, middle, right = ["gold", "iron", "lead"]
worksleft, right = ["gold", "iron", "lead"]
doesn'tleft, right = right, left
does a safe swapfor
loops to unpack structures on the flyelements = [ ['H', 'hydrogen', 1.008], ['He', 'helium', 4.003], ['Li', 'lithium', 6.941], ['Be', 'beryllium', 9.012] ] for (symbol, name, weight) in elements: print name + ' (' + symbol + '): ' + str(weight)
hydrogen (H): 1.008 helium (He): 4.003 lithium (Li): 6.941 beryllium (Be): 9.012
open
to open a file"r"
(for read) or "w"
for writeinput_file = open('count_bytes.py', 'r') content = input_file.read() input_file.close() print len(content), 'bytes in file'
121 bytes in file
Method | Purpose | Example |
---|---|---|
close | Close the file; no more reading or writing is allowed | input_file.close() |
read | Read N bytes from the file, returning the empty string if the file is empty. | next_block = input_file.read(1024) |
If N is not given, read the rest of the file. | rest = input_file.read() | |
readline | Read the next line of text from the file, returning the empty string if the file is empty. | line = input_file.readline() |
readlines | Return the remaining lines in the file as a list, or an empty list at the end of the file. | rest = input_file.readlines() |
write | Write a string to a file. | output_file.write("Element 8: Oxygen") |
write does not automatically append a newline. | ||
writelines | Write each string in a list to a file (without appending newlines). | output_file.writelines(["H", "He", "Li"]) |
Table 8.3: File Methods |
input_file = open('file.txt', 'r') output_file = open('copy.txt', 'w') line = input_file.readline() while line: output_file.write(line) line = input_file.readline() input_file.close() output_file.close()
file.txt
for reading, and assigns the file object to input_file
copy.txt
for writing, and assigns the file object to output_file
input_file
line
is assigned the empty stringoutput_file
input_file = open('count_lines.py', 'r') count = 0 for line in input_file: count += 1 input_file.close() print count, 'lines in file'
6 lines in file
input_file = open('file.txt', 'r') lines = input_file.readlines() input_file.close() output_file = open('copy.txt', 'w') output_file.writelines(lines) output_file.close()
input_file = open('file.txt', 'r') output_file = open('copy.txt', 'w') for line in input_file: line = line.rstrip() print >> output_file, line input_file.close() output_file.close()
print >> file
sends print
's output to a fileExercise 8.1:
What does "aaaaa".count("aaa")
return? Why?
Exercise 8.2:
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 8.3:
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-06 Python Software Foundation. | next |