How to create a numbered list across cells in jupyter notebook?

In a comment to a stackoverflow suggestion, you mention you are already cleaning the notebooks. So you probably wouldn’t mind another command in your notebook preparation pipeline?

So based on something similar to here you could make a python script with the following and then run that step in your preparation :

import nbformat as nbf
qtag = 'Q#.'
current_qnum = 1
ntbk = nbf.read("original_notebook.ipynb", nbf.NO_CONVERT)
cells_to_keep = []
for cell in ntbk.cells:
    if cell.cell_type == "markdown":
        if qtag in cell['source']:
            cell['source'] = cell['source'].replace(qtag,f"Q{current_qnum}.",1)
            current_qnum += 1
    cells_to_keep.append(cell)
new_ntbk = ntbk
new_ntbk.cells = cells_to_keep
nbf.write(new_ntbk, "qnumbered_notebook.ipynb", version=nbf.NO_CONVERT)

As written, it only replaces the first qtag it encounters in a cell. I did this because you described your cells as being different questions.

1 Like