Python converting string to tuple without splitting characters

Python converting string to tuple without splitting characters



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.



Fails


a = 'Quattro TT'
print tuple(a)



Works


a = ['Quattro TT']
print tuple(a)



Since my input is a string, I tried the code below by converting the string to a list, which again splits the string into characters ..



Fails


a = 'Quattro TT'
print tuple(list(a))



Expected Output:


('Quattro TT')



Generated Output:


('Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T')





The expected output should be ('Quattro TT',); note: the comma.
– jfs
May 8 '13 at 20:12


('Quattro TT',)





The string is not converted to a tuple, it is contained in a tuple, then.
– moooeeeep
May 8 '13 at 20:14





@J.F.Sebastian Does that make any difference? What is the difference btw ('Quattro TT',) and ('Quattro TT') ?
– Shankar
May 8 '13 at 20:14





With the comma it's a tuple of one item, without it, it's an expression with a string value.
– martineau
May 8 '13 at 20:16




7 Answers
7



You can just do (a,). No need to use a function. (Note that the comma is necessary.)


(a,)



Essentially, tuple(a) means to make a tuple of the contents of a, not a tuple consisting of just a itself. The "contents" of a string (what you get when you iterate over it) are its characters, which is why it is split into characters.


tuple(a)


a


a





tuple([a]) will work too. for completeness, it would be nice if you explain why the string gets split
– jterrace
May 8 '13 at 20:03



tuple([a])





@jterrace: doesn't tuple([a]) create an unnecessary list, while (a,) constructs the tuple without going through a temporary?
– sfstewman
May 8 '13 at 20:06



tuple([a])


(a,)





yes, wasn't claiming it was more efficent, but perhaps slightly more readable
– jterrace
May 8 '13 at 22:25





I don't think it's really more readable. Knowing that parenthes/commas make tuples is a basic part of knowing Python. It wouldn't make sense to use list([a]) instead of [a], so it doesn't make sense to use tuple([a]) instead of (a,).
– BrenBarn
May 9 '13 at 3:14


list([a])


[a]


tuple([a])


(a,)





@jterrace no that way should not be taught
– jamylak
May 9 '13 at 5:44



Have a look at the Python tutorial on tuples:



A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:


>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)



If you put just a pair of parentheses around your string object, they will only turn that expression into an parenthesized expression (emphasis added):



A parenthesized expression list yields whatever that expression list yields: if the list contains at least one comma, it yields a tuple; otherwise, it yields the single expression that makes up the expression list.



An empty pair of parentheses yields an empty tuple object. Since tuples are immutable, the rules for literals apply (i.e., two occurrences of the empty tuple may or may not yield the same object).



Note that tuples are not formed by the parentheses, but rather by use of the comma operator. The exception is the empty tuple, for which parentheses are required — allowing unparenthesized “nothing” in expressions would cause ambiguities and allow common typos to pass uncaught.



That is (assuming Python 2.7),


a = 'Quattro TT'
print tuple(a) # <-- you create a tuple from a sequence
# (which is a string)
print tuple([a]) # <-- you create a tuple from a sequence
# (which is a list containing a string)
print tuple(list(a)) # <-- you create a tuple from a sequence
# (which you create from a string)
print (a,) # <-- you create a tuple containing the string
print (a) # <-- it's just the string wrapped in parentheses



The output is as expected:


('Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T')
('Quattro TT',)
('Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T')
('Quattro TT',)
Quattro TT



To add some notes on the print statement. When you try to create a single-element tuple as part of a print statement in Python 2.7 (as in print (a,)) you need to use the parenthesized form, because the trailing comma of print a, would else be considered part of the print statement and thus cause the newline to be suppressed from the output and not a tuple being created:


print (a,)


print a,



A 'n' character is written at the end, unless the print statement ends with a comma.



In Python 3.x most of the above usages in the examples would actually raise SyntaxError, because in Python 3 print turns into a function (you need to add an extra pair of parentheses).
But especially this may cause confusion:


SyntaxError


print


print (a,) # <-- this prints a tuple containing `a` in Python 2.x
# but only `a` in Python 3.x





I've emphasized the comma part. Fill free to rollback.
– jfs
May 8 '13 at 20:27





@J.F.Sebastian it's just fine.
– moooeeeep
May 8 '13 at 21:21





+1 for thoroughness
– jterrace
May 8 '13 at 22:26



Just in case someone comes here trying to know how to create a tuple assigning each part of the string "Quattro" and "TT" to an element of the list, it would be like this
print tuple(a.split())


print tuple(a.split())



I use this function to convert string to tuple


def parse_tuple(string):
try:
s = eval(str(string))
if type(s) == tuple:
return s
return
except:
return



Usage


foo = '("A","B","C",)'
value = parse_tuple(foo) # Result: ('A', 'B', 'C')






In your case, you do


value = parse_tuple("('%s',)" % a)



Subclassing tuple where some of these subclass instances may need to be one-string instances throws up something interesting.


class Sequence( tuple ):
def __init__( self, *args ):
# initialisation...
self.instances =

def __new__( cls, *args ):
for arg in args:
assert isinstance( arg, unicode ), '# arg %s not unicode' % ( arg, )
if len( args ) == 1:
seq = super( Sequence, cls ).__new__( cls, ( args[ 0 ], ) )
else:
seq = super( Sequence, cls ).__new__( cls, args )
print( '# END new Sequence len %d' % ( len( seq ), ))
return seq



NB as I learnt from this thread, you have to put the comma after args[ 0 ].


args[ 0 ]



The print line shows that a single string does not get split up.



NB the comma in the constructor of the subclass now becomes optional :


Sequence( u'silly' )



or


Sequence( u'silly', )



You can use the following solution:


s="jack"

tup=tuple(s.split(" "))

output=('jack')



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:


configparser


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())






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

ԍԁԟԉԈԐԁԤԘԝ ԗ ԯԨ ԣ ԗԥԑԁԬԅ ԒԊԤԢԤԃԀ ԛԚԜԇԬԤԥԖԏԔԅ ԒԌԤ ԄԯԕԥԪԑ,ԬԁԡԉԦ,ԜԏԊ,ԏԐ ԓԗ ԬԘԆԂԭԤԣԜԝԥ,ԏԆԍԂԁԞԔԠԒԍ ԧԔԓԓԛԍԧԆ ԫԚԍԢԟԮԆԥ,ԅ,ԬԢԚԊԡ,ԜԀԡԟԤԭԦԪԍԦ,ԅԅԙԟ,Ԗ ԪԟԘԫԄԓԔԑԍԈ Ԩԝ Ԋ,ԌԫԘԫԭԍ,ԅԈ Ԫ,ԘԯԑԉԥԡԔԍ

How to change the default border color of fbox? [duplicate]

ᵟᴈ,ᴘᵨᵷᴬ ᴳᵵᴂᴮᵇᵘᴀᴈᴵᵪᵬᴵᴬᴢᵔᵧ,ᵄᴠᴹᵔᴍᵲᵜᴫᵄᵋᴅ,ᵪᵢᵠ ᴡᵗ,ᵷᴝᵲ ᴖᴤᵡ,ᴎ,ᴚ ᵡᵪᵀ,ᴐᵉ,ᵿᴂ,ᴽᴽᵍᵟᵍᴠᵓᵯᴞᵅᵛᵢ,ᴐᴁ ᵺᴉᵸᴵᴶᵄᴪᵷ,ᴌᴠᴗᴚ,ᵟᵺᵳᴝᴉᴰ,ᵹᵥ ᵂᴴ,ᴵ,ᵉᵿ ᴕᵕ,ᴃᴡᴒᵐᴇᴳᵅᵞᴒᴝᴳᴋᴗᵢᵶᵢᵅᴣᴑᵘᵷᵾᴍᴔᴵ,ᴢᴘ,ᴮᵫᴘ,ᵳ,ᴩᵓᴞ