0

How can I turn a string, say 'a' into a variable name on which I can use the append function?

I am trying to take the input, which is made ut of only small letters of the alphabet and record the posision of the letter in the string with a number under a variable of the letters name. The problem i have encountered is that I have to turn the string that i have from the input into a variable name that i can use the append funtion on. I have tried using vars() after I saw it somewhere (don't really know what vars() does since I'm new to this). This worked fine sometimes, but not always. Now I'm looking for a better way to do it.

'''This is the code i have now. This does not work all the time'''
ord = input()
count = 1
for i in ord:
    i = vars()[i]
    i.append(count)
    count = count + 1
    i = []
  • 4
    You don't! The better way to do it is to use a dictionary. Messing with local variables will bite you back at some point. – freakish Apr 30 '19 at 12:42
  • Check this https://stackoverflow.com/questions/19122345/to-convert-string-to-variable-name – skrubber Apr 30 '19 at 12:42
  • 2
    Possible duplicate of [To convert string to variable name](https://stackoverflow.com/questions/19122345/to-convert-string-to-variable-name) – Sociopath Apr 30 '19 at 12:43
  • What exactly are you trying to do here? – Devesh Kumar Singh Apr 30 '19 at 12:46
  • Your motivation is very vague. Can you describe what your ultimate goal is rather than how you tried to go about accomplishing it? (It sounds a bit like you want to count how many times a word has occurred in the input.) – molbdnilo Apr 30 '19 at 12:48
  • @freakish i can't because i may have more than two of one value. –  Apr 30 '19 at 12:50
  • [What is the XY problem?](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – Sayse Apr 30 '19 at 12:55
  • I don't understand what you're trying to achieve here, what does the number under a letter represent? – Sayse Apr 30 '19 at 13:01

3 Answers3

1

Here's a proper solution corresponding to what you are trying to do (which is letter indexing I think) using dictionaries:

result = {}
ord = input()  # why do you call that variable ord?
count = 1
for i in ord:
    if i not in result:
        result[i] = []
    result[i].append(count)
    count += 1
print(result)

No vars, no locals, no messing with an unsafe context. No problem when someone types i in your input and similar other issues. Everything safe and simple. It can be further simplified by the usage of defaultdict.

As a side note: forget about the existence of vars/locals/globals and similar objects. I've never had to use them even though I've been programming in Python for a decade. These are interesting when you write some crazy code like a Python debugger. Otherwise not needed. And these are swords that will cut you unless you're a samurai.

freakish
  • 54,167
  • 9
  • 132
  • 169
  • Also only ever used `locals` et al once and agree that they should only ever be considered when fully understand how scope affects an application – Sayse Apr 30 '19 at 13:10
0

You just need a dictionary that adds the indexes to a list, defaultdict is great for this

from collections import defaultdict
text = input()
result = defaultdict(list)
for idx, letter in enumerate(text):
     result[letter].append(idx)

print(result)

output for the string asdc would be {'a': [0], 'c': [3], 's': [1], 'd': [2]}

Sayse
  • 42,633
  • 14
  • 77
  • 146
-1

The vars() function returns a dictionary of all variables defined in the current context. You can use it to set values or append new values to lists. Check on the script bellow for an example:

data=[]
print("Field Name:")
field=input()
print("Value:")
ord1 = input()
print("VALUE: {}".format(field))
i = vars().get(field,None)
if i is not None:
    i.append(ord1)
print(data)

You can add values to this map using

vars()['key']='Value'

Result:

{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'key': 'Value', '__package__': None}
MUNGAI NJOROGE
  • 1,144
  • 1
  • 12
  • 25