Jed Rembold
October 18, 2021
What is the second element (index 1) in the below list?
[i * 4 for i in "Oct 18, 2020" if not i.isalpha()]
16"8888""cccc""1111"| Method | Description |
|---|---|
str.split() |
Splits the string str into a list of its components using whitespace as a separator |
str.split(sep) |
Splits the string str into a list using the specified separator sep |
str.splitlines() |
Splits the string str into a list of strings at the newline character |
str.join(list) |
Joins the (string) elements of the list into a string, using str as the separator |
with irl)with open(filename) as file_handle:
# Code to read the file using the file_handle
read reads the entire file in as a stringreadline or readlines reads a single line or lines from the fileread alongside splitlines gets you a list of line stringsread method reads the entire file into a string, with includes newline characters to mark the end of linesAs an example, the file:
One fish
two fish
red fish
blue fish
would get read as
"One fish\ntwo fish\nred fish\nblue fish"
with open(filename) as f:
for line in f:
# Do something with the line
read and then the splitlines method can be a good optionwith open(filename) as f:
lines = f.read().splitlines()
# Then you can do whatever you want with the list of lines
IOErroropen encounters an error, it reports the error by raising an exception with IOError as its type.
trytry statement to indicate an interest in trying to handle a possible exceptiontry:
# Code that may cause an exception
except type_of_exception:
# Code to handle that type of exception
type_of_exception here is the class name of the exception being handled
IOError for the file reading errors we are discussingtry block or within functions called within the try block would be “caught” and the lower block of code run instead of terminating the programdef get_existing_file(prompt="Input a filename: "):
while True:
filename = input(prompt)
try:
with open(filename):
return filename
except IOError:
print("That filename is invalid!")
open call succeeds, we immediately just return the filename, but if it fails due to a IOError, we display a message and then keep asking