ch 8 practice questions Flashcards
How many times is the letter ‘r’ printed below?
s = “strawberry”
idx = 1
while idx < len(s):
print(s[idx])
idx = idx + 2
1
What is printed?
s = “Ball”
s[0] = “C”
print(s)
Nothing, error
what does .find() do?
searches for the position of one string within another
it can also take a second index as to where it should start looking
ex. .find(‘na’, 3)
what does the following print?
line = ‘Have a nice day’
print(line.lower().startswith(‘h’))
True
What is printed?
s = “let’s go blue!”
print(s.count(“e”) + s.count(“b”))
3
What is parsing?
looking into a string and finding a substring
what types are the following used for?
1. %d
2. %g
3. %s
integer
floating point number
string
what does format operator % do?
allows us to construct strings, replacing parts of the strings with the data stored in variables; when operand is a string, % is the format operator
What is returned by the following?
str = “His shirt is red”
pos = str.find(“is”)
print(pos)
1; gives back 1st position of argument
What is printed by the following?
s1 = “heY”
s1 = s1.capitalize()
Hey
capitalize only uppercases the first letter
How do you know when ‘open’ is sucessful?
the system returns a file handle object, something that we can use to read data
What is a file handle?
an object used to read/ modify a file, not the actual data in the file
what is \n?
newline, breaks whatever ur typing into 2 lines
it counts as its own character
If you know the file is relatively small compared to the size of your main memory, you can read the whole file into one string using what?
read method; .read()
What is the difference between the 2 codes?
1)
fhand = open(‘mbox-short.txt’)
for line in fhand:
if line.startswith(‘From:’):
print(line)
fhand.close()
2)
fhand = open(‘mbox-short.txt’)
for line in fhand:
line = line.rstrip()
if line.startswith(‘From:’):
print(line)
fhand.close()
2) has line.strip(), which gets rid of the default newline in code 1
rstrip vs strip?
rstrip removes whitespace from the right side of the str, strip removes whitespace from left and right side of str
when ‘find’ returns a negative value, what does this mean?
the value could not be found
What parameters do you need for for the write function
filename and ‘w’
what does the write method do?
handle object puts data into the file, returning the number of characters written
why do you need the close functions?
to make sure that the last bit of data is physically written to the disk so it will not be lost if the power goes off
what does repr do?
takes any object as an argument and returns a string representation of the object
ex.
s = ‘1 2\t 3\n 4’
print(repr(s))
‘1 2\t 3\n 4’
What opening file format closes the file automatically when you leave the bock (indented area)?
with open(file) as name:
What is printed by the following? Why
print(‘ “1958”‘.strip(‘”’))
“1985
strip() removes both leading and trailing whitespace. Since you didn’t add a space before the quotes, it won’t remove the leading “