contextlib.redirect_stdout in Python
Level 4210 keystrokes
This redirects stdout to a StringIO buffer to capture print output.
Python code
# redirect_stdout temporarily sends print output elsewhere1from contextlib import redirect_stdout# StringIO is a text stream kept in memory2from io import StringIO3 # Create an empty buffer to collect the output4buffer = StringIO()# Inside this block, print writes to buffer instead of the screen5with redirect_stdout(buffer): # Nothing is shown; "Hello\n" goes into the buffer6 print("Hello")7 print("World")8 # Read everything written so far: 'Hello\nWorld\n'9captured = buffer.getvalue()# stdout is restored; repr() shows the newlines as \n10print(f"Captured: {repr(captured)}")Output
Captured: 'Hello\nWorld\n'
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
(× 7)× 7"× 6_× 2:× 2=× 2.× 1{× 1}× 1