diff --git a/IPython/nbformat/v2/nbpy.py b/IPython/nbformat/v2/nbpy.py
index 243bc65..8d89fc0 100644
--- a/IPython/nbformat/v2/nbpy.py
+++ b/IPython/nbformat/v2/nbpy.py
@@ -24,7 +24,7 @@ from .nbbase import new_code_cell, new_text_cell, new_worksheet, new_notebook
# Code
#-----------------------------------------------------------------------------
-_encoding_declaration_re = re.compile(r"^#\s*coding[:=]\s*([-\w.]+)")
+_encoding_declaration_re = re.compile(r"^#.*coding[:=]\s*([-\w.]+)")
class PyReaderError(Exception):
pass
@@ -113,7 +113,7 @@ class PyReader(NotebookReader):
class PyWriter(NotebookWriter):
def writes(self, nb, **kwargs):
- lines = [u'# coding: utf-8']
+ lines = [u'# -*- coding: utf-8 -*-']
lines.extend([u'# 2',''])
for ws in nb.worksheets:
for cell in ws.cells:
diff --git a/IPython/nbformat/v2/tests/nbexamples.py b/IPython/nbformat/v2/tests/nbexamples.py
index 6b6dd28..3e83e8e 100644
--- a/IPython/nbformat/v2/tests/nbexamples.py
+++ b/IPython/nbformat/v2/tests/nbexamples.py
@@ -81,7 +81,7 @@ nb0 = new_notebook(
metadata=md
)
-nb0_py = """# coding: utf-8
+nb0_py = """# -*- coding: utf-8 -*-
# 2
#