Joseph Wahba Joseph Wahba - 1 year ago 89
Python Question

Python converting a string to comma separated tuple

I am having a string options="1110000000" and I want to convert it to comma separated tuple as follows options_converted = ('1', '1', '1', '0', '0', '0', '0', '0', '0', '0').

What came to my mind is using something like this

(options[i:i+n] for i in range(0, len(options), 1))

but it gives me

generator object at 0x...

So I thought of a more simplified way to do so

options_converted = ()
for i, j in enumerate(options):
options_converted = options_converted + str(j)

But obviously that doesn't work because I haven't initialize options_converted as a tuple with at least one element.

Any suggestions ?

Answer Source

You can do it like this:

print tuple("1110000000")


('1', '1', '1', '0', '0', '0', '0', '0', '0', '0')

Return a tuple whose items are the same and in the same order as iterable‘s items. iterable may be a sequence, a container that supports iteration, or an iterator object. If iterable is already a tuple, it is returned unchanged. For instance, tuple('abc') returns ('a', 'b', 'c') and tuple([1, 2, 3]) returns (1, 2, 3). If no argument is given, returns a new empty tuple, ().

tuple is an immutable sequence type.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download