I got a problem when appending a dict to list
data = []
path = "abc\cde"
data.append({"image": path})
print(data)
When I append the path to the image, the output of data is [{'image':'abc\def'}]. It contains two \ instead of one.
CodePudding user response:
\
is an escape character. It allows you to use special symbols, for example a new line \n
or tab \t
. If you want a string to contain a literal \
, make sure that you put another \
before it.
In your case, Python understands that you meant "abc\\cde"
even though you did not escape \
. If you had abc\nde
, the result would be abc<line_break>de
.
>>> a = "abc\\cde"
>>> a
'abc\\cde'
>>> list(a)
['a', 'b', 'c', '\\', 'c', 'd', 'e']
As you see, even though it looks like a double backslash, it is just one \
character.
More info: https://www.w3schools.com/python/gloss_python_escape_characters.asp
CodePudding user response:
The additional backslash is Python escaping the single backslash. The actual value of your path
string is unchanged, as you can see when the value of data[0]['image']
is printed.
data = []
path = 'abc\cde'
data.append({"image": path})
# output: abc\cde
print(data[0]['image'])
CodePudding user response:
When typing text that contains slashes, use raw strings to avoid having some sequences be interpreted as special characters, e.g. "\n"
in a python string is a single character that represents a new line.
>>> data = []
>>> data.append({"image": r'abc\cde'})
>>> data
[{'image': 'abc\\cde'}]
>>>
>>> data.append({"image": r'abc\nasdf'})
>>> data
[{'image': 'abc\\cde'}, {'image': 'abc\\nasdf'}]
When you see two slashes is because that's how python repr
-esents a string with slashes safely, it's not the actual content.
>>> r'abc\cde'
'abc\\cde'
>>> r'abc\nasdf'
'abc\\nasdf'
In this way a text with special chars can be visualized in a compact way. If you want to see what the actual content of those strings looks like, print
them:
>>> print(r'abc\cde')
abc\cde
>>> print(r'abc\nasdf')
abc\nasdf
>>> print('abc\cde')
abc\cde
>>> print('abc\nasdf')
abc
asdf