MongoDB.live, free & fully virtual. June 9th - 10th. Register Now MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

Pymongo and Python string escape characters

Hey folks,

I have been stumped by what I presume is a pretty simple issue. One of the fields in my documents is a MS windows-style UNC path ie: "unc_path": "\\server\share\path\file"

We are using Atlas and if I take a look within compass or the Atlas web UI I see what needs to be there. But when I perform a find for this info, db.collection.find({}, {"unc_path": 1}) a python escaped string is returned for each result, ie:
image

Is there a way to request that raw text be returned for these values or any other reasonable work around?

Thanks!

Hi James,

What you’re seeing is the way Python prints out string values in dictionaries - this isn’t something PyMongo is doing.

Python prints dict values using repr, which shows a Python string with backslashes escaped. If you take your document and run print(doc['unc_path'] you’ll see it without the escaped backslashes.

# Note the 'r' prefix in the following string, which allows you to avoid escaping the backslashes:
In [1]: my_string = r"\not\a\path"

In [2]: print(my_string)
\not\a\path

In [3]: my_string
Out[3]: '\\not\\a\\path'

In [4]: a_dict = { 'key': my_string}

In [5]: a_dict
Out[5]: {'key': '\\not\\a\\path'}

In [6]: print(a_dict)
{'key': '\\not\\a\\path'}
3 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.