Python Strings and Files: Practice Questions
For each snippet, write the output. If it prints nothing, write “No Output”.
Practice the operations from the Strings and Files reading. Use the encoding reference chart for character lookups; you may bring a printed copy to an open-note quiz. Character-code memorization and hand conversion between number bases are not required. File questions create their own input files in the current working directory.
Basic String Operations
Indexing and slicing of strings works similarly to indexing and slicing of lists. The main difference is that the type of the result when indexing/slicing a string is always another string.
Question 1
s = 'hello world'
print(s[:-6])Answer
hello
Question 2
s = '12345'
xs = [1, 2, 3, 4, 5]
b = s[-1] == xs[-1]
print('b=', b)Answer
b= False
Question 3
s = 'hello'
xs = ['h', 'e', 'l', 'l', 'o']
b = s[-2:] == xs[-2:]
print('b=', b)Answer
b= False
Question 4
s = 'python is awesome'
if 'python' in s:
print('True')
else:
print('False')Answer
True
Question 5
s = 'python is awesome'
if 'Python' in s:
print('True')
else:
print('False')Answer
False
Python strings support a number of methods that lists do not support. It is important to remember that strings are immutable, and so methods will never change the content of a string.
Question 6
s = 'python is awesome'
t = s.replace('python', 'everything')
print('t=', t)Answer
t= everything is awesome
Question 7
s = 'python is awesome'
s.replace('python', 'everything')
print('s=', s)Answer
s= python is awesome
Question 8
s = 'python is awesome'
t = s.split()
u = t[-1]
print('u=', u)Answer
u= awesome
Question 9
s = 'python\nis\tawesome'
t = s.split()
u = ' '.join(t)
print('u=', u)Answer
u= python is awesome
Question 10
s = 'python is\tawesome'
t = s.split(' ')
u = t[1]
print('u=', u)Answer
u=
Question 11
s = 'python is awesome'
t = s.split('o')
u = 'XXX'.join(t)
print('u=', u)Answer
u= pythXXXn is awesXXXme
Question 12
s = 'guido van rossum'
i = s.find(' ')
t = s[:i]
print('t=',t)Answer
t= guido
Question 13
s = 'guido van rossum'
i = s.find('G')
t = s[:i]
print('t=',t)Answer
t= guido van rossu
Characters and Encodings
Question 14
print(chr(ord('a') - 32))Answer
A
Question 15
print(chr(ord('f') - 3))Answer
c
Question 16
s = '\x48\x45\x4C\x4C\x4F'
print('s=', s)Answer
s= HELLO
Question 17
s = 'cat\n'
print(len(s))
print(repr(s))Answer
4
'cat\n'
Question 18
data = 'cat'.encode('utf-8')
print(data)
print(data.decode('utf-8'))Answer
b'cat'
cat
Question 19
text = 'café'
data = text.encode('utf-8')
print(len(text))
print(len(data))Answer
4
5
Reading and Writing Files
Opening with mode 'w' creates or empties a file. Writing does not add a newline automatically. A with block closes the file when the block ends. Reading advances the file’s position; another read at the end returns an empty string.
Question 20
with open('poem.txt', 'w', encoding='utf-8') as f:
f.write('cat\nmat\n')
with open('poem.txt', encoding='utf-8') as f:
contents = f.read()
print(repr(contents))Answer
'cat\nmat\n'
Question 21
with open('colors.txt', 'w', encoding='utf-8') as f:
f.write('red,green,blue')
with open('colors.txt', encoding='utf-8') as f:
colors = f.read().split(',')
print(colors[1])Answer
green
Question 22
with open('note.txt', 'w', encoding='utf-8') as f:
f.write('cat')
with open('note.txt', encoding='utf-8') as f:
first = f.read()
second = f.read()
print(repr(first))
print(repr(second))Answer
'cat'
''
Question 23
with open('note.txt', 'w', encoding='utf-8') as f:
f.write('old text')
with open('note.txt', 'w', encoding='utf-8') as f:
f.write('new')
with open('note.txt', encoding='utf-8') as f:
print(f.read())Answer
new
Question 24
with open('words.txt', 'w', encoding='utf-8') as f:
f.write('sun')
f.write('rise')
with open('words.txt', encoding='utf-8') as f:
print(f.read())Answer
sunrise
Question 25
with open('poem.txt', 'w', encoding='utf-8') as f:
f.write('cat\nmat\n')
with open('poem.txt', encoding='utf-8') as f:
for line in f:
print(repr(line))Answer
'cat\n'
'mat\n'
Short Markdown Examples
These two examples combine find and slicing from the reading. The supplied strings have one matching pair of markers. Trace the positions and the slice before writing the output.
Question 26
line = 'one *two* three'
start = line.find('*')
end = line.find('*', start + 1)
print(line[start + 1:end])Answer
two
Question 27
def compile_bold(line):
start = line.find('**')
end = line.find('**', start + 2)
return line[:start] + '<b>' + line[start + 2:end] + '</b>' + line[end + 2:]
print(compile_bold('one **two** three'))Answer
one <b>two</b> three
Markdown Tracing Challenges
These longer functions prepare you for the Markdown compiler project. They include correct and incorrect implementations. First trace a matching pair of markers, then check what happens to an unmatched marker. For the loops, keep track of i, end, and result after each iteration. Compare related versions: a small change can preserve, remove, or stop processing the remaining text.
Question 28
def compile_italic_star(line):
result = ''
i = 0
while i < len(line):
if line[i] == '*':
if i + 1 < len(line) and '*' in line[i+1:]:
end = line.find('*', i+1)
result += '<i>' + line[i+1:end] + '</i>'
i = end + 1
else:
result += '*'
i += 1
else:
result += line[i]
i += 1
return result
result = compile_italic_star('alpha *beta* gamma *delta')
print(result)Answer
alpha <i>beta</i> gamma *delta
Question 29
def compile_italic_star(line):
result = ''
i = 0
while i < len(line):
if line[i] == '*':
end = line.find('*', i+1)
if end != -1:
result += '<i>' + line[i+1:end] + '</i>'
i = end + 1
else:
i = len(line)
else:
result += line[i]
i += 1
return result
result = compile_italic_star('alpha *beta* gamma *delta')
print(result)Answer
alpha <i>beta</i> gamma
Question 30
def compile_italic_star(line):
result = ''
i = 0
while i < len(line):
if line[i] == '*':
end = line.find('*', i+1)
if end != -1:
result += '<i>' + line[i+1:end] + '</i>'
i = end + 1
else:
i = len(line)
else:
result += line[i]
i += 1
return result
result = compile_italic_star('alpha *beta* gamma *delta*')
print(result)Answer
alpha <i>beta</i> gamma <i>delta</i>
Question 31
def compile_italic_star(line):
result = ''
i = 0
while i < len(line):
if line[i] == '*':
end = line.find('*', i+1)
if end != -1:
result += '<i>' + line[i+1:end] + '</i>'
i = end + 1
else:
i = len(line)
else:
result += line[i]
i += 1
return result
result = compile_italic_star('alpha *beta gamma delta')
print(result)Answer
alpha
Question 32
def compile_italic_star(line):
result = ''
i = 0
while i < len(line):
if line[i] == '*':
end = line.find('*', i+1)
if end != -1:
result += '<i>' + line[i+1:end] + '</i>'
i = end + 1
else:
i += 1
else:
result += line[i]
i += 1
return result
result = compile_italic_star('alpha *beta* gamma *delta')
print(result)Answer
alpha <i>beta</i> gamma delta
Question 33
def compile_italic_star(line):
result = ''
i = 0
while i < len(line):
if line[i] == '*':
end = line.find('*', i+1)
if end != -1:
result += '<i>' + line[i+1:end] + '</i>'
i = end + 1
else:
i += 1
else:
result += line[i]
i += 1
return result
result = compile_italic_star('alpha *beta gamma delta')
print(result)Answer
alpha beta gamma delta
Question 34
def compile_italic_star(line):
result = ''
i = 0
while i < len(line):
if line[i] == '*':
end = line.find('*', i+1)
if end != -1:
result += '<i>' + line[i+1:end] + '</i>'
i = end + 1
else:
i += 1
else:
result += line[i]
i += 1
return result
result = compile_italic_star('alpha *beta gamma delta*')
print(result)Answer
alpha <i>beta gamma delta</i>
Question 35
def compile_bold_stars(line):
start = line.find('**')
if start == -1 or len(line) < 4:
return line
end = line[start + 2:].find('**')
if end == -1:
return line
end = end + start + 2
return line[:start] + '<b>' + line[start + 2:end] + '</b>' + line[end + 2:]
result = compile_bold_stars('alpha **beta** gamma **delta**')
print(result)Answer
alpha <b>beta</b> gamma **delta**
Question 36
def compile_bold_stars(line):
start = line.find('**')
if start == -1 or len(line) < 4:
return line
end = line[start + 2:].find('**')
if end == -1:
return line
end = end + start + 2
return line[:start] + '<b>' + line[start + 2:end] + '</b>' + line[end + 2:]
result = compile_bold_stars('alpha **beta** gamma **delta')
print(result)Answer
alpha <b>beta</b> gamma **delta
Question 37
def compile_bold_stars(line):
start = line.find('**')
if start == -1 or len(line) < 4:
return line
end = line[start + 2:].find('**')
if end == -1:
return line
end = end + start + 2
return line[:start] + '<b>' + line[start + 2:end] + '</b>' + line[end + 2:]
result = compile_bold_stars('alpha beta gamma **delta')
print(result)Answer
alpha beta gamma **delta