sentence = input("Input sentence: ")
punctuation = [" ", ",", ".", ":", "?", "!"]
interruption1 = sentence.index(punctuation)
word1 = sentence[:interruption1]
print(word1)
In this question, the main aim is to have the program print the first word that the user types by identifying a character that implies the first word has ended (the punctuation characters in the ‘punctuation’ variable). I want the program to accept the ‘punctuation’ variable within the index function but it sends an error message saying "must be str, not list". I tried for loops, they don’t work here either as far as I know.
A previous question of mine gave me information that you can’t use boolean values to represent a set of values in a variable, so I used a list, but now this error happens, and there is absolutely nothing on the Internet on this sort of problem (neither do I have an IT teacher or any friends that do Python), so I had to come here after about an hour of trying random combinations of code. How do I make Python accept the list and use it inside the index function? Thank you.
>Solution :
You don’t need to use an index unless it is demanded; just keep accepting characters from the sentence until you come to a punctuation. So the simplest looping approach is:
sentence = input("Input sentence: ")
punctuation = [" ", ",", ".", ":", "?", "!"]
result = ""
for c in sentence:
if c in punctuation:
break
else:
result = result + c
print(result)