3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Python】ヒアドキュメントでエスケープシーケンスを展開する

Last updated at Posted at 2020-03-03

ハマったので備忘。

ヒアドキュメントにそのままエスケープシーケンス(\)を書いてもエスケープシーケンスとして展開されない。

\\のように2つ続けて記述するか、raw文字列を使うと展開できる。

>>> import json
>>>
>>> json_dict1 = json.loads('''
... {
...     "id": 1,
...     "name": "hoge",
...     "description": "ほげ\"ほげ\"ほげ"
... }
... ''')
Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 5 column 24 (char 59)
>>> print(json_dict1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'json_dict1' is not defined
>>>
>>> json_dict2 = json.loads('''
... {
...     "id": 2,
...     "name": "hoge",
...     "description": "ほげ\\"ほげ\\"ほげ"
... }
... ''')
>>> print(json_dict2)
{'id': 2, 'name': 'hoge', 'description': 'ほげ"ほげ"ほげ'}
>>>
>>> json_dict3 = json.loads(r'''
... {
...     "id": 3,
...     "name": "hoge",
...     "description": "ほげ\"ほげ\"ほげ"
... }
... ''')
>>> print(json_dict3)
{'id': 3, 'name': 'hoge', 'description': 'ほげ"ほげ"ほげ'}
3
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?