-2

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

Community
  • 1
  • 1
ddbg
  • 37
  • 1
  • 3
  • 12
  • You are **replacing** the `string` argument with tuple, so it won't matter what you pass in. And what did you expect `if 'A':` and `if 'B':` to test? Both of those are *always* going to be true. – Martijn Pieters Aug 29 '14 at 17:14
  • What did you add `string = 'A', 'B'` for here, what did you expect it to do? That binds the name `string` to a tuple with two elements, `'A'` and `'B'` (the comma makes that a tuple). Whatever it was bound to before (when calling the function) is now no longer available. – Martijn Pieters Aug 29 '14 at 17:16

3 Answers3

2

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')
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • Ohhh so the tuple, being a list, doesn't allow the code to operate as a string? It is not recognizing or pulling out the individual parts? – ddbg Aug 29 '14 at 17:24
  • If you want to get the count of the string passed in just call count on the string, setting string = "A","B" means the variable you passed is never used as you reassign the name to your tuplr – Padraic Cunningham Aug 29 '14 at 17:27
1

Because count is a method/module (whatever it's called in python) for string, the way you do it,

myString ='A','B'

myString is a tuple, not a string.

RockOnRockOut
  • 751
  • 7
  • 18
1

first, here is the correct version of your code:

def percentLetters(string):      
    print string.count('A')  
    print string.count('B')

second, you don't use two strings in an assignment to one variable unless you want to make it a string tuple.

Amen
  • 1,524
  • 5
  • 22
  • 41