# Helene Martin, Garfield High School # Demonstrates strings # Strings are lists of characters. Most things done with a list can be done with a string. # Strings can't be modified (no append or pop allowed!) # Anything between quotes is a string my_string = "Hello" print(my_string) # String characters can be indexed print(my_string[3]) #prints 'l' # We can slice strings print(my_string[3:5]) #prints 'lo' # We can loop over a string for letter in my_string: print(letter) # We can replace a part of the string # Note that since strings can't be modified, we have to save the result new_string = my_string.replace("lo", "macaroni") print(new_string) # prints Helmacaroni # Find a substring in a string print(my_string.find("lo")) # prints 3 (found at index 3) print(my_string.find("z")) # prints -1 (not found) print(my_string.lower()) # to lowercase print(my_string.upper()) # to uppercase # Test for a certain suffix if(my_string.endswith("ed")): print("Probably a past-tense verb") else: print("Probably not a past-tense verb") # Can split a string on a particular identifier. # VERY useful for reading datafiles my_data = "bobby,1995,10,23,45,10" data_list = my_data.split(",") print(data_list) # We can center the string to make our printouts pretty print(my_string.center(80)) # centers on an 80-character line