Practice: Multiline Strings
Q1. Three-line message
Create a multiline string holding the lines one, two and three and print it.
Goal: Create multiline strings.
Q2. Count the lines
Print how many lines the text """a\nb\nc\nd""" has by using splitlines (write it with triple quotes and real line breaks).
Goal: Count lines.
Q3. Quotes inside
Print a triple-quoted string that contains both 'single' and "double" quote marks on one line.
Goal: Use quotes inside triple quotes.
Q4. Skip first newline
Write a string that starts on a new line in the code but does not begin with a new line; it should contain hello then a newline then world. Print its repr.
Goal: Control the start of a string.
Q5. Join long text
Using parentheses and adjacent literals, print the single line: Learn Python step by step.
Goal: Join adjacent literals.
Q6. Number the lines
Print each line of the text with its number starting at 1, for the lines red, green and blue.
Goal: Process lines.
Q7. Dedent text
Use textwrap.dedent to print the text below with no leading spaces: two lines indented by four spaces, hello and world.
Goal: Use dedent.
Q8. Template letter
Given name = "Ravi" print two lines: Hello Ravi, and Welcome! using a triple-quoted f-string.
Goal: Use f-strings with triple quotes.
Q9. Build from list
Join the words in ["x", "y", "z"] into a three line string and print it.
Goal: Join lines.
Q10. Hidden newline
What does this print?
s = """
hi
"""
print(len(s))Goal: Count hidden characters.
Q11. Lines count
What does this print?
s = """a
b
c"""
print(s.count("\n"), len(s.splitlines()))Goal: Count line breaks.
Q12. Repr shows all
What does this print?
s = """x
y"""
print(repr(s))Goal: Read repr.
Q13. Adjacent pieces
What does this print?
t = ("ab"
"cd" "ef")
print(t, len(t))Goal: Predict adjacent literals.
Q14. Backslash continuation
What does this print?
s = """one \
two"""
print(s)Goal: Read continuation.
Q15. Docstring access
What does this print?
def f():
"""Say hi."""
return 1
print(f.__doc__)Goal: Know docstrings.
Q16. Unclosed string
This code has a SyntaxError. Fix it so it prints two lines.
print("""line one
line two")Goal: Close strings correctly.
Q17. Extra indent
The output has four unwanted spaces on each line. Fix the code so it prints hello and world with no spaces at the left.
def show():
text = """
hello
world
"""
print(text.strip())
show()Goal: Remove indentation.
Q18. Missing space
This prints Hello,world. It should print Hello, world. Fix it.
print("Hello,"
"world")Goal: Fix joined literals.
Q19. Why dedent
Explain why textwrap.dedent is useful for multiline strings in functions.
Goal: Explain dedent.
Q20. Triple vs plus
Explain the difference between a triple-quoted string and parentheses with adjacent literals.
Goal: Choose a string style.