0

I want to add single backslash element to my list. I used print("\\") and it printed single backslash; however, when I try to add "\\" to my list, it adds double backslash. How can I solve this problem?

You can see the code below:

signs=["+","x","÷","=","/","\\","$","€","£","@","*","!","#",":",";","&","-","(",")","_","'","\"",".",",","?"]

print("Signs:",signs)

I use the Python 3.7.3 IDLE as IDE.

From now, thanks for your attention!

Phy_Mat11
  • 9
  • 1
  • 1
  • 4
  • 2
    Could you include the code you are actually using? – rayt Feb 01 '22 at 09:09
  • Be careful not to confuse the actual string and the python representation of the string. If you print the value in your list this will be a single backslash. – mozway Feb 01 '22 at 09:11
  • When you try to add `'\'` it should give you a `SyntaxError`. Note that a single backslash `'\\'` is represented just the same way, so the string *representation* is different from the actual string. – a_guest Feb 01 '22 at 09:11
  • It's only putting a single backslash in the list. But when you print a list, it shows the representation of the strings in the list, so they're printed with double backslashes. – Barmar Feb 01 '22 at 09:11
  • And as a side note, have a look at [string.punctuation](https://docs.python.org/3/library/string.html#string.punctuation) which gives you '!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~' and although not necessary, you can pass it to list() in order to convert it to list. – buran Feb 01 '22 at 09:22

2 Answers2

1

Using a Python REPL

>>> ll = [1,2,3]
>>> ll.append('\\')
>>> ll
[1, 2, 3, '\\']
>>> ll[3]
'\\'
>>> print(ll[3])
\
>>>

If Python displays a string it needs to Escape the backslash, put if you print the element it shows a single backslash

rioV8
  • 24,506
  • 3
  • 32
  • 49
0

Your code print the list as a whole:

signs=["+","x","÷","=","/","\\","$","€","£","@","*","!","#",":",";","&","-","(",")","_","'","\"",".",",","?"]

print("Signs:",signs)

gives:

Signs: ['+', 'x', '÷', '=', '/', '\\', '$', '€', '£', '@', '*', '!', '#', ':', ';', '&', '-', '(', ')', '_', "'", '"', '.', ',', '?']
[]

Use * to print it 'one by one'. * is the unpacking operator that turns a list into positional arguments, print(*[a,b,c]) is the same as print(a,b,c).

signs=["+","x","÷","=","/","\\","$","€","£","@","*","!","#",":",";","&","-","(",")","_","'","\"",".",",","?"]

print("Signs:",*signs)

enter image description here

Ka Wa Yip
  • 2,546
  • 3
  • 22
  • 35