0

When I tried appending a string containing a backslash into a list, the element in the list is actually the string, but with double backslashes instead of single backslashes.

Code is as follows:

word = "<< hello\world"
sample = list()
sample.append(word)
print(sample) #['<< hello\\world']
print word #<< hello\world

Can anybody explain what is going on, and how to work around this?

CodeBender
  • 35,668
  • 12
  • 125
  • 132
Binh Phan
  • 69
  • 7

1 Answers1

0

The backslash is a special character, you should have written it with 2 backslashes yourself. Python corrected you. If you try to print the item within the list it will print correctly.

print(sample) #['<< hello\\world']
print word #<< hello\world
print(sample[0]) #<< hello\world
Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62