Sequences are a series of values in a particular order
In Python predominantly strings and lists but also sets and tuples
Strings
Sequence of characters (characters are strings of length 1)
Strings are immutable; really important for functions
Basic string operations
+, concatenation for strings
*, repetition repeats given value
len() returns length of sequence
s in str returns True if s is a substring of str, False otherwise
Indexing, var[position]
Count from 0 to len(var)−1
Position can be a negative number to count from right
Assignment with indexing doesn’t work as strings immutable x = ’hEllo’; x[1] = ’e’ produces an error
Slicing, var[start:end]
Value at index end not included in slice
If omitted, starting value defaults to 0 and ending value defaults to last index + 1
Can use negative index
Looping over strings: for i in str
Example program [strstuff.py]
String methods
Rule: methods that change, add, or delete characters do not alter the string to which they are applied; they return a new string that is a copy of the old string, suitably modified
String methods: type of characters in string (return True or False) [strtype.py]
S.isalpha() — True if only alphabetics (letters) in S
S.isalnum() — True if only alphanumerics (letters or digits) in S
S.isdigit() — True if only digits in S
S.isspace() — True if only white space (blanks, tabs, newlines) in S
S.isupper() — True if all letters in S are upper case
S.islower() — True if all letters in S are lower case
String methods: changing case of letters in string (return result of applying method) [strchcase.py]
S.capitalize() — If the first character of S is a letter, capitalize it
S.title() — Capitalize each word in \str
S.lower() — Change all upper case letters in S to lower case
S.upper() — Change all lower case letters in S to upper case
S.swapcase() — Change all upper case letters in S to lower case and vice versa
String methods: stripping blanks from strings (return result of applying method) [strstrip.py]
S.lstrip() — Delete all leading white spaces from S
S.rstrip() — Delete all trailing white spaces from S
S.strip() — Delete all leading and trailing white spaces from S
String methods: find characters and substrings (return position or cause exception) [strfind.py]
S.find(s) — Return the index of the first occurrence of s in S; −1 if s not in S
Sindex(s) — Return the index of the first occurrence of s in S; ValueError exception if s not in S
Srfind(s) — Return the index of the last occurrence of s\ in S; −1 if s not in S
Srindex(s) — Return the index of the last occurrence of s in S; ValueError exception if s not in S
String methods: miscellaneous [strmisc.py]
S.count(s) — Return the number of times s occurs in S
S.startswith(s) — True if S starts with s
S.endswith(s) — True if S ends with s
S.replace(s,t) — Replace all occurrences of s with t in S
Matt Bishop
Department of Computer Science
University of California at Davis
Davis, CA 95616-8562 USA