Converting string to tuple without splitting characters

169,706

Solution 1

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.

Solution 2

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

Solution 3

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)

Solution 4

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

Solution 5

You can use the following solution:

s="jack"

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

output=('jack')
Share:
169,706
Shankar
Author by

Shankar

Senior Data Scientist @LexisNexis | Pythonista

Updated on August 09, 2021

Comments

  • Shankar
    Shankar over 2 years

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