Max577
Max577

Reputation: 5

Convert a string to a set without splitting the characters

I have a quick question: a='Tom', a type of str. I want to make it into a set with one item. If I use the command b = set(a), I got a set with 3 items in it, which is set(['m',''T','o']). I want set(['Tom']). How could I get it? Thanks.

Upvotes: 0

Views: 3056

Answers (3)

Blender
Blender

Reputation: 298392

The set builtin makes sets out of iterables. Iterating over a string yields each character one-by-one, so wrap the string in some other iterable:

set(['Tom'])
set(('Tom',))

If you're used to the mathematical notation for sets, you can just use curly braces (don't get it confused with the notation for dictionaries):

{'Tom'}
{'Tom', 'Bob'}

The resulting sets are equivalent

>>> {'Tom'} == set(['Tom']) == set(('Tom',))
True

Upvotes: 1

jramirez
jramirez

Reputation: 8685

Like this:

a = "Tom"

b = set([a])

Upvotes: 0

null
null

Reputation: 11879

set(['Tom'])

You just answered your own question (give list, instead of string).

Upvotes: 0

Related Questions