1

I transport data from command line to python. And I want to convert from string (command line) to tuple (python). But I have problem with \ charactor.

In command line, I using:

C:\>python music.py -a variable="?=="

In python:

#convert variable to array 
variable_array = variable.split("==")
#convert to tuple
variable_tuple = tuple(variable_array)

I get variable_tuple = ("?","")

The result what I need is variable_tuple = ("\?","")

When using

C:\>python music.py -a variable="\?=="

The result is variable_tuple = ("\\?","")

How can I transport data from command line to get tuple ("\?","") in python? I need backslash for "?"

hoangvu68
  • 845
  • 2
  • 13
  • 28

4 Answers4

4

'\\?' is a string with one backslash character and a question mark. Using list is a convenient trick for spliting a string into characters. For example:

In [34]: list('\\?')
Out[34]: ['\\', '?']

shows '\\?' is composed of 2 characters, not 3. And if you print it:

In [35]: print('\\')
\

you see it prints as just one backslash character. The double backslash, '\\', is an escape sequence.


Note also that when you print a tuple, you get the repr of its contents:

In [36]: print(tuple('\\?'))
('\\', '?')

'\?' is the exact same string as '\\?' in Python. They are simply different ways of representing the same string:

In [38]: list('\?')
Out[38]: ['\\', '?']

In [39]: list('\\?')
Out[39]: ['\\', '?']    

In [42]: '\?' is '\\?'
Out[44]: True
Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • If input is "\\?", we will get ("\\\\?") – hoangvu68 Jan 06 '13 at 12:49
  • @hoangvu68: I don't have Windows to check, but yes, I believe so. – unutbu Jan 06 '13 at 12:54
  • @unutbu: I need backslash for "?" ("\?"). I don't want to add backslash before "\". – hoangvu68 Jan 06 '13 at 13:01
  • You need to make a clear distinction between the way strings are represented, eg `'\\?'`, and the way they are printed, e.g. `\?`. If you want a **single** backslash followed by a question mark, then the way that string is **represented** in Python is `'\\?'`. – unutbu Jan 06 '13 at 13:07
  • 1
    Python chooses to represent this string as `'\\?'` even though `'\?'` represents the same string. You won't be able to change the way Python behaves in this respect without hacking the source code and recompiling Python. – unutbu Jan 06 '13 at 13:11
  • @unutbu: Thank you. I resloved it :) – hoangvu68 Jan 06 '13 at 14:13
0

You get exactly what you want. What you see is just the string represenation for '\' with the first '\' as escape character.

0

("\\?","") means that the '\' is escaped, otherwise '\?' would be interpreted as escape sequence.

ConfusedProgrammer
  • 606
  • 1
  • 5
  • 14
0

?need not to be backslashed. So what you get is right and enough.

mayaa
  • 173
  • 1
  • 2
  • 10