Professional Documents
Culture Documents
05.strings and Sequences
05.strings and Sequences
Strings
Prof. Snyder Fall 2011 George Mason University
one_string = ABC
another_string = ABC These represent two distinct, unique string data.
Sequence Operations
(all sequences, not just strings)
Membership
Repetition
Indexing
Indexing
Accessing the 0th indexed element of a_string
10
Indexing (Loops)
The variable i takes on the value of each successive element of the sequence during each successive iteration of the loop Limitation: can only iterate through the sequence elements in order
11
Length
12
Indexing (Loops)
The variable i takes on the value of each successive element of the range during each successive iteration of the loop
13
Indexing (Loops)
The variable i takes on the value of each successive element of the sequence during each successive iteration of the loop More robust: can iterate through the sequence elements in any manner
14
Slicing
15
Slicing
Strange...
16
Practice what are these expressions Problem Using indexes and slices,
values?
word = "dysfunctional"
'y' 'fun' 'functional' 'unction' 'l' 'me' 'meat' 'tea' 't' 'totem'
group = "team"
word[1] word[3:6] word[3:] word[4:11] word[len(word)-1] group[-1:-4:-2] group[-1:-4:-2]+group[-2::-2] group[:3] group [-len(group)] word[-6:-3:2]+group[:2]+group[3]
Min / Max
Why?
18
ASCII Table
20
Min / Max
21
String Methods
Method: an action or process (defined relative to a particular object) to be performed
Dot Operator: a dot (period) that is used to access an associated variable or call an associated function
object_name.method_name
strVar = Test
Refer to Library Reference: 5.6.1
methods: operate on a single data type string object methods (e.g., capitalize) strVar.capitalize()
23
String Formatting
def main(): x = input("Enter number: ) print "counter =", x y,z = "counter = ", str(x); print y + z print "counter = " + str(x) y = "counter = " + str(x); print y print "counter = %d" % (x) y = "counter"; print "%s = %d" % (y,x) z = "%s = %d" % (y,x); print z w = " = "; z = "%s%s%d" % (y,w,x); print z main()
24
Enter number: 3 counter = 3 counter = 3 counter = 3 counter = 3 counter = 3 counter = 3 counter = 3 counter = 3
Tuples
(a quick introduction)
String Formatting
(Characters that may follow a % for special meaning)
26
Practice Problem
What is the resulting string? Are there any errors? "I have %d apples." % 15 'I have 15 apples.' "%d / %f = %f" % (7, 3.0, 7/3.0) / 3.000000 = 2.333333' '7 x = "%d %s"; x % (3, "amigos") amigos' '3 "%%d prints integers." % () '%d prints integers.' "I %s MadLibs" % (love) (love is not defined) "%f %d %s" % (4,4.6,"""yo""") '4.000000 4 yo' "%s %x" % (hex(200),200) '0xc8 c8' "%d centimeters is %d inches." '%d centimeters is %d inches'