LukeP_8
LukeP_8

Reputation: 309

How to print unique words from an inputted string

I have some code that I intend to print out all the unique words in a string that will be inputted by a user:

str1 = input("Please enter a sentence: ")

print("The words in that sentence are: ", str1.split())

unique = set(str1)
print("Here are the unique words in that sentence: ",unique)

I can get it to print out the unique letters, but not the unique words.

Upvotes: 3

Views: 25841

Answers (4)

tmak920
tmak920

Reputation: 1

You can us this code:

str1 = input("Please enter a sentence: ")
print("The words in that sentence are: ", str1.split(' '))
str2=str1.split(' ')
unique = set(str2)
print("Here are the unique words in that sentence: ",unique)

Upvotes: 0

Jan
Jan

Reputation: 432

Another way of doing it:

user_input = input("Input: ").split(' ')

duplicates = []

for i in user_input:
    if i not in duplicates:
        duplicates.append(i)

print(duplicates)

Upvotes: 0

Ukimiku
Ukimiku

Reputation: 618

Also, you can use:

from collections import Counter

str1 = input("Please enter a sentence: ")
words = str1.split(' ')
c = Counter(words)
unique = [w for w in words if c[w] == 1]

print("Unique words: ", unique)

Upvotes: 0

Jordan McQueen
Jordan McQueen

Reputation: 787

String.split(' ') takes a string and creates a list of elements divided by a space (' ').

set(foo) takes a collection foo and returns a set collection of only the distinct elements in foo.

What you want is this: unique_words = set(str1.split(' '))

The default value for the split separator is whitespace. I wanted to show that you can supply your own value to this method.

Upvotes: 10

Related Questions