Issue
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.
Solution
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.
Answered By - Jordan McQueen Answer Checked By - Pedro (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.