'''lecture_22_strings_template.py Demonstrate string properties and reading from and writing to a file by reading in and manipulating Chapter 1 of Alice in Wonderland, stored in a text file. Oliver W. Layton CS 151: Computational Thinking: Visual Media Spring 2021 ''' '''Reading text from a file''' # Our goal: load in from text from a file to work with in Python (Chapter 1 of Alice In Wonderland). # Process of loading text from file into a string called "reading text from a file" # theFile = open('alice_chapter_1.txt', 'r') # firstLineStr = theFile.readline() # theFile.close() # Make file object and read in one line. # print('First line:', firstLineStr) # Then read TWO lines. # File object keeps track of which lines you have already read in so when you call readline() the # second time, it remembers that you already read the first line (so won't read 1st line twice). # theFile = open('alice_chapter_1.txt', 'r') # firstLineStr = theFile.readline() # secondLineStr = theFile.readline() # theFile.close() # print('First line:', firstLineStr) # print('Second line:', secondLineStr) # To read in entire chapter: automate with loop. We don't know how many lines the line has # Can use the empty string '' as loop sentinel: What readline() returns when we reach end of file. aliceList = [] theFile = open('alice_chapter_1.txt', 'r') currentLineStr = theFile.readline() while currentLineStr != '': # print(currentLineStr) aliceList.append(currentLineStr) currentLineStr = theFile.readline() theFile.close() # Print out first few items of list (first few lines of file) # print(aliceList[:4]) '''Escape sequences''' # What are the \n things doing at the end of each string in the list? We don't see them in file! # \n is an ESCAPE SEQUENCE, a "special code" in the string, in this case to mean new line. # Example: print out 1st line. # abc = "a\n\n\nb\n\n\nc" # print(abc) # print(aliceList[0]) # print('Alices Adventures in Wonderland\n') # print('See the new line above!') # We can use them in our own strings too! # Example: Print a string variable with new lines. # # Text: 'Haikus are easy. But sometimes they dont make sense. Refrigerator.' # haiku = 'Haikus are easy.\nBut sometimes they dont make sense.\nRefrigerator.' # print(haiku) # Print function automatically tacks on \n to string we print (otherwise multiple print statements # would bunch text up on same line!). # Example: Print lines of haiku separately. # print('Haikus are easy.') # print('But sometimes they dont make sense.') # print('Refrigerator') # Print allows us to turn this off by setting keyword argument end='' (empty string): # print('Haikus are easy.', end='') # print('But sometimes they dont make sense.', end='') # print('Refrigerator', end='') # Tabs: \t # haiku = 'Haikus are easy.\tBut sometimes they dont make sense.\tRefrigerator.' # print(haiku) # Apostrophes or quotes in strings: \' or \" # Example: Missing quote in haiku # haiku = 'Haikus are easy.\nBut sometimes they don\'t make sense.\nRefrigerator.' # print(haiku) # Show how mixed quotation symbols also work (recent versions of Python only) # haiku = "Haikus are easy.\nBut sometimes they don't make sense.\nRefrigerator." # print(haiku) '''Length''' # Example: How many characters are in the 1st line of Alice in Wonderland? print(aliceList[:2]) # print(len(aliceList[0])) # testExample = 'a bc\n' # both whitespace (hitting spacebar) and \n count as 1 character each # print(len(testExample)) # ...but this includes the new line character! How can we get rid of it? # print(aliceList[0]) # Option 1) Slice a string: treat string like list of characters # Example: What is the length of the new line character? print('length of new line character:', len('\n')) # Accessing single characters # We can also use the "list indexing approach" to extract single characters or ranges (substrings) firstLine = aliceList[0] # print(firstLine) # print(firstLine[:5]) myStr = 'abc' print(myStr[1:]) # Example: Extract substring: "Alice" from 1st line # Print Alice # print(aliceList[0][:5]) # Print out 1st line starting with Adventures... print(firstLine[8:]) # The string without the new line print(firstLine[:-1]) # Option 2) Strip string method '''Looping through strings''' # We can loop thru strings, not just range and lists: # Example: Print every character of 1st line of Alice on separate line '''String operators''' # Concatenation: + operator with two strings # Example: Concatenate 1st two lines of Alice # print(firstTwo) # What if we wanted the two on the same line? # print(firstTwo) # Example: Use concatenation to build up single BIG string of the file '''Important string methods: Join and split''' # 1) Join: list of strings -> one string # What if we wanted to take the list of lines and make one big string out of it? # Example: How many characters are in entire chapter? # Smaller example: 1st 3 lines of alice # print(first3) # Example: Adding periods (or any string) between first 3 lines, adding new line back between lines # print(first3) # 2) Split: one string -> list of strings # Example: extract words from 1st line of Alice # print(line1Split) # Example: Take big single string of Alice and split it up into a list of separate lines like before # print(lines) '''Writing to a text file''' # Let's make a new text file and write the first two lines of Alice to it. # Example: Fix lines bunching up on 1 line. # Example: Write all lines to the file '''Time permitting extras''' '''Check if string contains substring''' # Determine whether a string (the subtring) appears / doesn't appear inside another one # Text: 'two wrongs don\'t make a right' # Text: 'right' # a = 'two wrongs don\'t make a right' # b = 'right' '''Other string methods''' # Strings are technically objects and have methods. There are many: # https://docs.python.org/3/library/stdtypes.html#string-methods) # Here are important ones that you should know (minimally): # upper, lower, title, split(char), join, find(word), replace, count # isalpha, isdigit, isupper, isalnum # Example: Let's see some string methods in action. # Replace: Example, replace word 'We' with 'I'. Print it out. # Count: Find total number of Is in chapter