I'm working on zybook labs here is question:
Write a program whose input is a string which contains a character and a phrase, and whose output indicates the number of times the character appears in the phrase.
Ex: If the input is:
n Monday the output is: 1
Ex: If the input is: z Today is Monday
the output is: 0
Ex: If the input is: n It's a sunny day
the output is: 2
Case matters.
Ex: If the input is: n Nobody
the output is: 0
n is different than N.
My codes works only in half way here is code:
user_input = input()
words_list = user_input.split() # to put user input into list
word = words_list[0] # to take character for counting
new_list = words_list.pop(1) # to make new list without character for count
count = new_list.count(word) # count character in new_list
print(count)
my code works for inputs: n Monday, z Today is Monday. It doesn't work for inputs: n It's a sunny day, t this is a sentence with many t's
I have no idea why it doesn't work for other inputs.
CodePudding user response:
When you do this:
new_list = words_list.pop(1)
That takes the second word in the list and stores it into new_list
. The rest of the words are still in words_list
, but you don't check them.
And actually, you don't need to split this at all.
user_input = input()
target = user_input[0]
count = user_input[2:].count(target)
CodePudding user response:
user_input = input()
words_list = user_input.split(" ", 1) # to put user input into list
word = words_list[0] # to take character for counting
new_list = words_list.pop(1) # to make new list without character for count
count = new_list.count(word) # count character in new_list
print(count)
See if it solves the problem