Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove '>>> ' from copied and pasted doctest

Reading documentations I often encounter doctests that I would like to run. Let's say you want to run the following in a Jupyter notebook:

>>> a = 2
>>> b = 3
>>> c = a + b

What is the fastest way to do it?

like image 886
Diego Sacconi Avatar asked Dec 06 '25 09:12

Diego Sacconi


1 Answers

Just copy and paste it in a new cell. Jupyter strips such markup for you when it runs the sample:

enter image description here

If you must strip the markup (for aesthetic reasons, perhaps), you can use a bit of Python code to do so:

def extract_console_code(sample):
    return ''.join([l[4:] for l in sample.splitlines(True) if l[:4] in ('>>> ', '... ')])

print(extract_console_code(r'''<paste code here>'''))

Note the r raw string literal! This should work for most Python code. Only if your code sample contains more ''' triple-single-quotes would you have to handle those separately (by using double quotes around the code, or by concatenating sections together with different string literal styles). Also, note that we skip any line that doesn't start with >>> or ...; those are output lines and not code.

You'll have to run this in a Python script, because the Jupyter console still just strips those initial lines away, and so for your exact example, depending on how you added the lines, it could be that none or only a few of the lines are returned; any line starting with >>> or ..., even in a string literal, will have been stripped by Jupyter already!

like image 93
Martijn Pieters Avatar answered Dec 08 '25 21:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!