MIGUEL GP
MIGUEL GP

Reputation: 63

Separate each letter from a text without saving the same letter twice

I wanted to know how I could separate a text in the different letters it has without saving the same letter twice in python. So the output of a text like "hello" will be {'h','e',l','o'}, counting the letter l only once.

Upvotes: 1

Views: 69

Answers (2)

Ben
Ben

Reputation: 6348

As the comments say, put your word in a set to remove duplicates:

>>> set("hello")
set(['h', 'e', 'l', 'o'])

Iterate through it (sets don't have order, so don't count on that):

>>> h = set("hello")
>>> for c in h:
...   print(c)
...
h
e
l
o

Test if a character is in it:

>>> 'e' in h
True
>>> 'x' in h
False

Upvotes: 1

hill_sprints
hill_sprints

Reputation: 16

There's a few ways to do this...

word = set('hello')

Or the following...

letters = []

for letter in "hello":
    if letter not in letters:
        letters.append(letter)

Upvotes: 0

Related Questions