Use Count to count the number of characters in two separate strings

Viewed 57

I am trying to use count to count the number of characters in two separate strings. I can get it to work for just one but how can I format it to count for two strings? I have tried using 'and' but it is not working. What I want is when the user enters inputs for name1(Anna) and name2(Andy) I want the result to be 3 counting the letter 'a' in both names.

name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
lower1 = name1.lower()
lower2 = name2.lower()
a = lower1.count("a") and lower2.count("a")
print(a)
4 Answers

and is boolean operator.

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

You want to use addition

a = lower1.count("a") + lower2.count("a")

You can also first concatenate the two strings and then count:

a = (lower1 + lower2).count("a")

I suppose you want to add the two counts, right? So simply:

a = lower1.count("a") + lower2.count("a")
print(a)

should be enough in your case.

and is a boolean operator, which cant be used when assigning variables with the sum of two other variables. The correct way is:

a = lower1.count("a") + lower2.count("a")
Related