I'm trying to take in string input and count them but exclude certain characters but it seems to be counting all the characters no matter what I do.
user_text = input()
count = 0
for i in user_text:
if i in user_text != 'a':
count = 1
print(count)
CodePudding user response:
You should check if i
is not equal to a
if i != 'a':
CodePudding user response:
Did you try with just
if i != 'a':
CodePudding user response:
More "pythonic" way could be:
user_text = input()
count = len([True for x in user_text if x != 'a'])
print(count)
CodePudding user response:
What you are doing is chaining comparison operators which is not what you want. Because your statement is the same as:
(i in user_text) and (user_text != 'a')
The first statement is always True, because you iterate over every character in user_text
.
The second statement is only False, when the user_text
is a
. You can try this by entering an a
as input.
So to achieve what you want, you should use this statement as in other answers already suggested:
if i != 'a'
Small side note: It could help your understanding when you rename i
to something like char
, because i
is most often used in for-loops that count from 0 to n. e.g. fo i in range(10)