I am writing a code to count the occurrences of each letter within a string. I understand that it has been asked and answered Count occurrence of a character in a string, however I cannot figure out why it will not count when I use it.
def percentLetters(string):
string = 'A','B'
print string.count('A')
print string.count('B')
If I was to input percentLetters('AABB')
, I would anticipate receiving A=2 and B=2 but am having no such luck. I tried using an if
statement earlier however it would not print anything at all
def percentLetters(string):
string='A','B'
if 'A':
print string.count('A')
if 'B':
print string.count('B')
This doesn't work either. Anyone who might have some insight it would be helpful
Don't reassign string
inside the function and better to not use string
as a variable name at all.
def percentLetters(s):
print s.count('A')
print s.count('B')
percentLetters('AABB')
2
2
string = 'A','B'
means you set the string variable to a tuple containing just ("A","B")
, it is not pointing to the string
you pass in.
In [19]: string = 'A','B'
In [20]: string
Out[20]: ('A', 'B')
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments