Download Computer Science Cheat Sheet and more Cheat Sheet Computer Science in PDF only on Docsity! CS150 - Final “Cheat Sheet” 1 Input/Output • Reading input from the user raw input(message): Displays message to the user and return what the user typed as a string • Reading from a file file = open(filename, "r") for line in file: # do something file.close() • Writing to a file – Opening a file for writing: file = open(filename, "w") # begin writing from the beginning # or file = open(filename, "a") # append to the end of the existing contents – the write method writes strings and other objects to the opened file (without and carriage return) • Reading from URLs (e.g. web pages) import urllib web_page = urllib.urlopen(some_url) for line in web_page: # do something 1 • Command-line arguments import sys sys.argv is a list containing the command-line arguments. 2 Strings • The following functions are built-in and answer questions about strings – len(string): Returns the number of characters in the string – int(string) float(string): Converts a string to an int or float • String object methods – upper() lower(): Returns a new string that is upper or lower cased – find(some string): Returns the index that some string occurs at in the string or -1 if it does not occur. – find(some string, index): Same as above, but starts searching at index – replace(old, new): Return a copy of the string with all occurrences of old substituted with new – startswith(prefix): Returns True if the string starts with prefix, False otherwise – endswith(prefix): Returns True if the string ends with prefix, False otherwise – strip(): Returns a copy of the string with leading and trailing whitespace removed – split(): Return a list of the words in the string using a space as the delimiter • String operators – string1 + string2: Returns a new string that is the concatenation of string1 and string2 – string * int: Returns a new string that is string repeated int times 3 Lists • Creating new lists – [] creates an empty list – [object1, object2, object3, ...] Creates a list containing the objects • The following functions are built-in and answer questions about lists – len(list): Returns the number of entries in the list 2