I have a config file that has a string which is tab separated. I want to retrieve that string and then convert that to a nice list. But, I am seeing some interesting things that I do not see when I do it directly on iPython.
[myvars]
myString = "a\tb\tc\td"
.....
.....<many more variables>
My Python code has this:
param_dict = dict(config.items(myvars))
str1 = param_dict["myString"]
print str1
print str1.split()
And it prints out this:
"a\tb\tc\td"
['"a\\tb\\tc\\td"']
But, when I do the same thing on my python console, I get what I expect:
Python 2.7.6 (default, Mar 22 2014, 22:59:38)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> "a\tb\tc\td".split()
['a', 'b', 'c', 'd']
>>> k = "a\tb\tc\td"
>>> k.split()
['a', 'b', 'c', 'd']
What is going on here? Can someone help me out? I cannot change the format of the config file variables. And, I want to get the variable out and strip into a nice list.
Thanks.
The backslash is being read in here, you don't see this when you print the plain string, but do if you print the repr.
In [11]: myString = "a\\tb\\tc\\td"
In [12]: print(myString)
a\tb\tc\td
In [13]: print(repr(myString))
'a\\tb\\tc\\td'
You can use decode to convert \\t to \t:
In [14]: myString.decode('string_escape')
Out[14]: 'a\tb\tc\td'
Once they are tabs you can split on them:
In [15]: myString.split()
Out[15]: ['a\\tb\\tc\\td']
In [16]: myString.decode('string_escape').split()
Out[16]: ['a', 'b', 'c', 'd']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With