Chapter 8 Working with Sequences: Strings and Lists Section 8.1 and 8.2 Bonita Sharif 1
Sequences A sequence is an object that consists of multiple data items These items are stored consecutively Examples A string This is a string Ali list numbers = [ a, b, c ] 2
Types of Sequences Strings Sequences that hold characters Strings are immutable Lists Sequences that hold various types of data Dynamic data items Lists are mutable 3
Iterating over a String A for loop is used for iterating over a string of characters General Form for variable in string: statement t t : Examples sentence = The quick brown fox jumps over the lazy dog for char in sentence: print char See count_ts.py for another example 4
String Indexing A string s s characters can be referenced using an index. The index is a number that denotes the position of the character in the string Id Indexing starts t from 0 It is given inside square brackets. [ ] 5
String Indexing Examples my_string = I love Python Programming ch = my_string[8] print ch # negative index points to characters relative to the end of the string print my_string[-1] print my_string[ string[-4] # causes an IndexError exception print my_string[25] # Prints the length of the string print len(my_string) 6
IndexError Exception This exception occurs if you try to use an invalid index in a string. 7
String Length You can use the len() function to determine the length of a string Example strlen = len(my_string) The len() function is used in while loops to determine the end of a string. Example index = 0 while index < len(my_string) statement index += 1 8
Strings are Immutable Concatenation doesn t really change the original string What really happens? You cannot change a particular character in a string my_ string[1] = i # error 9
String Slicing A string slice consists of part of a string String slice is also called a substring To slice a string you specify the start and end in [start:end] There are several ways you can do this If start is left out, it defaults to 0 If end is left out, it defaults to string length 10
String Slicing If both indices are left out, then the first index defaults to 0 and the second index defaults to the length of the string Step value in string slicing It causes characters to be skipped in the string. Invalid indices do not raise exceptions. If start is > than end it returns an empty string If start or end dindex does not exist 11
Examples full_name = Patty Lynn Smith middle_name = full_name[6:10] first_name = full_name[:5] last_name = full_name[11:] my_string1 = full_name[:] my_string2 = full_name[0: len(full_name)] my_string3 = full_name[0:16:3] step value 12
Book Examples generate_login.py login.py 13
String Containment You can test to see if a string contains another string using the in and not in operators. General format string1 in string2 string1 not in string2 14
Example word = fox sentence = The quick brown fox jumped if text in sentence: print Found else: print Not Found 15
String Methods A method is a function that belongs to an object. It does some operations on the object. In this case the object is a string. String Methods to Test strings Modify strings Search and replace substrings 16
String Testing Methods isalnum(): isalpha() isdigit() il islower() isspace() isupper() (string_test.py) test 17
String Modification Methods lower() lstrip(), lstrip(char) rstrip(), rstrip(char) strip(), strip(char) h upper() swapcase() 18
Case Insensitive Comparisons continue = y while continue.lower() == y : do something continue = raw_input( Do you want to continue? Enter y or n: ) 19
Searching and Replacing Methods endswith(substring) find(substring) replace(old, new) startswith(substring) ih( i 20
An Example Ask the user to enter a password Validate the password to meet the following criteria Passwords must be At least 7 characters long Contain at least 1 uppercase letter Contain at least 1 lowercase letter Contain at least 1 numeric digit See login.py and validate_password.py py 21
The Repetition Operator Besides multiplication, * also denotes the repetition operator. When used between a string and a number it denotes the repetition operator. Example my_string ti = b * 5 See repetition_operator.py 22
Exercises string = I am a string. Hello string.rstrip( Helo. ) # What is the content of variable string? string.upper() # What is the content of variable string? string = string.rstrip( Helo. ) # What is the content of variable string? 23
Converting a String to a List string = I am a string mylist = string.split() split() The result will be a list containing i 4 elements [ I, am, a, string ] 24