I am striving to convert a string to a tuple without splitting the characters of the string in the process. Can somebody suggest an easy method to do this. Need a one liner.
This only covers a simple case:
a = ‘Quattro TT’
print tuple(a)
If you use only delimiter like ‘,’, then it could work.
I used a string from configparser
like so:
list_users = (‘test1’, ‘test2’, ‘test3’)
and the i get from file
tmp = config_ob.get(section_name, option_name)
>>>”(‘test1’, ‘test2’, ‘test3’)”
In this case the above solution does not work. However, this does work:
def fot_tuple(self, some_str):
# (‘test1’, ‘test2’, ‘test3’)
some_str = some_str.replace(‘(‘, ”)
# ‘test1’, ‘test2’, ‘test3’)
some_str = some_str.replace(‘)’, ”)
# ‘test1’, ‘test2’, ‘test3’
some_str = some_str.replace(“‘, ‘”, ‘,’)
# ‘test1,test2,test3’
some_str = some_str.replace(“‘”, ‘,’)
# test1,test2,test3
# and now i could convert to tuple
return tuple(item for item in some_str.split(‘,’) if item.strip())
See:
'Quattro TT'
is a string.
Since string is a list of characters, this is the same as
['Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T']
Now...
['Quattro TT']
is a list with a string in the first position.
Also...
a = 'Quattro TT'
list(a)
is a string converted into a list.
Again, since string is a list of characters, there is not much change.
Another information...
tuple(something)
This convert something into tuple.
Understanding all of this, I think you can conclude that nothing fails.
I use this function to convert string to tuple
import ast
def parse_tuple(string):
try:
s = ast.literal_eval(str(string))
if type(s) == tuple:
return s
return
except:
return
Usage
parse_tuple('("A","B","C",)') # Result: ('A', 'B', 'C')
In your case, you do
value = parse_tuple("('%s',)" % a)