Converting string to tuple without splitting characters
Asked Answered
I

9

61

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')
Inch answered 8/5, 2013 at 20:0 Comment(4)
The expected output should be ('Quattro TT',); note: the comma.Halfcock
The string is not converted to a tuple, it is contained in a tuple, then.Acierate
@J.F.Sebastian Does that make any difference? What is the difference btw ('Quattro TT',) and ('Quattro TT') ?Inch
With the comma it's a tuple of one item, without it, it's an expression with a string value.Chicanery
C
97

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

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.

Ciliate answered 8/5, 2013 at 20:0 Comment(5)
tuple([a]) will work too. for completeness, it would be nice if you explain why the string gets splitCtesiphon
@jterrace: doesn't tuple([a]) create an unnecessary list, while (a,) constructs the tuple without going through a temporary?Noblewoman
yes, wasn't claiming it was more efficent, but perhaps slightly more readableCtesiphon
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,).Ciliate
@Ctesiphon no that way should not be taughtSanious
A
21

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:

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:

print (a,)            # <-- this prints a tuple containing `a` in Python 2.x
                      #     but only `a` in Python 3.x
Acierate answered 8/5, 2013 at 20:18 Comment(2)
I've emphasized the comma part. Fill free to rollback.Halfcock
@J.F.Sebastian it's just fine.Acierate
V
18

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)
Vitiligo answered 6/7, 2017 at 8:29 Comment(0)
T
5

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

Taphole answered 13/9, 2013 at 23:31 Comment(0)
M
3

You can use the following solution:

s="jack"

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

output=('jack')
Meenen answered 18/8, 2018 at 12:16 Comment(0)
B
3

You can use eval()

>>> a = ['Quattro TT']  
>>> eval(str(a))
['Quattro TT']
Bifoliolate answered 16/9, 2020 at 19:2 Comment(0)
R
0

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 ].

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', )
Rupiah answered 7/12, 2015 at 12:10 Comment(0)
V
-1

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())
Verena answered 13/12, 2017 at 15:1 Comment(0)
A
-1

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.

Allegra answered 22/5, 2020 at 17:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.