简体   繁体   中英

String of list or strings to a tuple

I've got a class attribute which can be either a string or a list of strings. I want to convert it into a tuple such that a list converts normally, but a single string becomes a single-item tuple:

[str, str] --> (str, str)

str --> (str, )

Unfortunately tuple('sting') returns ('s', 't', 'r', 'i', 'n', 'g') which is not what I expect. Is it possible to do it without type checking?

Type checking would be a great way to achieve this. How would you otherwise decide if the input was a list or a string?.

You could make a function which tests if the input is a list or a string and returns appropriately and handles the rest as you see fit. Something along the lines of

>>> def convert_to_tuple(elem):
        if isinstance(elem, list):
            return tuple(elem)
        elif isinstance(elem, basestring):
            return (elem,)
        else:
            # Do Something
            pass


>>> convert_to_tuple('abc')
('abc',)
>>> convert_to_tuple(['abc', 'def'])
('abc', 'def')

You could only check for strings too, (Assuming Python 2.x, replace basestring with str in Py3)

>>> def convert_to_tuple(elem):
        if isinstance(elem, basestring):
            return (elem,)
        else:
            return tuple(elem)


>>> convert_to_tuple('abc')
('abc',)
>>> convert_to_tuple(('abc', 'def'))
('abc', 'def')
>>> convert_to_tuple(['abc', 'def'])
('abc', 'def')

Converting the function to a one liner is possible too.

>>> def convert_to_tuple(elem):
        return (elem,) if isinstance(elem, basestring) else tuple(elem)

You can do this:

>>> s = 'str'
>>> print (s,)
('str',)

There's no need to call tuple() when dealing with strings to achieve what you're trying.

If you need one method to help both types, then you can't avoid type checking:

def tuplising(typ):
    return tuple(typ) if isinstance(typ, list) else (typ,)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM