0

This is my first computer related class EVER. We're on week 2, chapter 2 and I need to:

"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."

Really simple, right? Well, i can't for the life of me figure out what is wrong with my program. I've separated out the part I think is the problem:

user_string = input()
user_character = user_string[0][0]

times = user_string.count('user_character') # problem line #

print(user_string)
print(user_character)
print(times)

input:

t Just trying to find all the ts.

expected output:

t Just trying to find all the ts.
t
5

actual output:

t Just trying to find all the ts.
t
0 <<< Why 0?
bereal
  • 32,519
  • 6
  • 58
  • 104
  • 1
    You don't need the quotes around `user_character`. (Also `[0][0]` is the same as `[0]` in this case, but it's not the cause of the problem) – bereal Mar 12 '23 at 13:32
  • Does this answer your question? [Count the number of occurrences of a character in a string](https://stackoverflow.com/questions/1155617/count-the-number-of-occurrences-of-a-character-in-a-string) – Jorge Luis Mar 12 '23 at 14:48

3 Answers3

0

Removing ' from 'user_character' in third line will work

user_string = input()
user_character = user_string[0][0]

times = user_string.count(user_character) # problem line #

print(user_string)
print(user_character)
print(times)
sourin_karmakar
  • 389
  • 3
  • 10
0

A few issues:

  • A string is a 1-dimensional string, but your code indexes it as if it is 2-dimensional, so drop one [0]. Note that [0][0] will work because the result of the first one is still a string, so in theory you can go on like that and write user_string[0][0][0][0], but it is already what you need to get after the first [0].

  • The argument to count should not be literal string 'user_character', but the name (without quotes)

  • The count should exclude the very first character (which is not part of the string that follows after the first space), so subtract one.

user_string = input()
user_character = user_string[0]   # a string has only one dimension

# pass the name (not a literal) and subtract one to ignore the very first character
times = user_string.count(user_character) - 1

print(user_string)
print(user_character)
print(times)
trincot
  • 317,000
  • 35
  • 244
  • 286
0

str.count() takes string as an argument (Ref: docs link), which you are providing.

However you are providing a literal string 'user_character', what you need to pass is the variable user_character (without single quotes) who's value changes as per your input string.

Anujith Singh
  • 116
  • 1
  • 7