DougKruger
DougKruger

Reputation: 4624

Python convert list of one element into string with bracket

How to convert python list containing one element to string with bracket? For more than one element, its easy for me to just just use tuple(list['a','b']) which returns as tuple ('a','b') but if element is one, it returns as ('a',) but rather I want to return ('a') sample:

mylist = ["a", " b"]
print tuple([s.strip() for s in mylist])
>> ('a', 'b')

mylist = ["a"]
print tuple([s.strip() for s in mylist])
>> ('a', ) #rather I want to return ('a')

Upvotes: 3

Views: 12827

Answers (2)

Moses Koledoye
Moses Koledoye

Reputation: 78554

>>> ('a') == 'a'
True

If you're not going to use a single element tuple, then the parenthesis are only grouping parenthesis (not a container), and they won't stick like you want them to, except you include them as part of the string with a or define a custom print function.

With the custom print function, you get to keep the conversion from list to tuple (i.e. t = tuple(mylist)) as is and also use the single element tuple as is:

def tuple_print(t):
    print(str(t).replace(',', '') if len(t) == 1 else t)

Trials:

>>> def tuple_print(t):
...      print(str(t).replace(',', '') if len(t) == 1 else t)
...
>>> mylist = ["a"]
>>> t = tuple(mylist)
>>> t
('a',)
>>> tuple_print(t)
('a')
>>> t = ('a', 'b')
>>> tuple_print(t)
('a', 'b')

Upvotes: 2

Eloims
Eloims

Reputation: 5224

Avoid relying on default __repr__() method, to format strings, they might change.

Be explicit about your intent instead

 print "('" + "', '".join(mylist) + "')"

Upvotes: 7

Related Questions