简体   繁体   中英

Convert from string to tuple with “\” in python

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 "?"

'\\\\?' 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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM