Home > Net >  How to add single backslash to a Python list?
How to add single backslash to a Python list?

Time:02-01

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!

CodePudding user response:

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

CodePudding user response:

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

  •  Tags:  
  • Related