-1

Sorry, i don't know how to name this problem correctly :/ I have variables for each letter in alphabet. When i check word for each letter i want to add +1 to the variable which is named the same as a letter im at currently. I want it to work like this: locals(letter) += 1

2 Answers2

4

It's not wise to have variables created for all letters in English and using them (26 variables! Sounds huge).

Better go for Counter approach:

from collections import Counter

word = 'hello'
print(Counter(word))
# Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})

If you need all letters count:

import string
from collections import Counter

all_letters = string.ascii_lowercase
word = 'hello'
d = dict.fromkeys(all_letters, 0)
d.update(Counter(word))
print(d)
Austin
  • 25,759
  • 4
  • 25
  • 48
1

You can access the variables by doing this...

locals()[letter]

But the fact you need to check the value of variables named after strings indicates a bad design choice.

Instead you should store those values in a dict.

letters = {
    'a': 0,
    'b': 0,
    'c': 0,
    ...
}

letters['a'] += 1
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73