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
Asked
Active
Viewed 49 times
-1

Stanisław Borkowski
- 37
- 5
2 Answers
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
-
I need each letter count for other calculation so this would only make it more difficult i guess, this was my first idea when i started, thanks tho :) – Stanisław Borkowski Dec 08 '18 at 14:41
-
@StanisławBorkowski, I edited my answer. Use the last code snippet in that case. – Austin Dec 08 '18 at 14:45
-
better, but still not what i need XD https://pastebin.com/kgqbfDD7 this is what im doing – Stanisław Borkowski Dec 08 '18 at 14:52
-
its for this (don't spoil it and write your answer please) https://adventofcode.com/2018/day/2 – Stanisław Borkowski Dec 08 '18 at 14:55
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