LukeP_8 LukeP_8 - 1 month ago 5
Python Question

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.

Answer

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.