Python Forum

Full Version: remove apostrophes in list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Is there a way to remove apostrophes in list so that this:

a_list = ['mary', 'had', 'a', 'little', 'lamb']
becomes:

a_list = [mary, had, a, little, lamb]
Thank you
I'm sure that you have tried a number of options.

This may not give you the complete solution but what about, rebuilding the list along this idea:

 b_list = a_list[0]+"  "+a_list[1]+" "+a_list[2]
etc.

Giving you a result of:
b_list =  mary had a little lamb
Obviously you can add back any commas, but as my experience is python limited, I not sure of how to ensure that the b_list becomes a true list with [] etc.

Can you give us an idea of your reasons as this may help with a solution.
But then they wouldn't be strings anymore, and it'd suddenly become invalid syntax. What are you REALLY trying to do? :p
Fair enough. In a previous post (else-statement-not-executing) it was intimated that a preferred method within menus was the use of dictionaries. Which is fine, if the dictionary is hard coded, however, in my particular case, neither the 'key' nor the value are known in advance. As you say, every attempt I try always puts the 'value' back as a string.

It's not a deal breaker, as the 'eval' option mentioned in the previous post solves the problem, just wanted to know if it was possible.
If the object you're trying to refeclarence is contained within a class/object/module, you could use getattr() to find it:
>>> class Spam:
...   def foo(self):
...     return "bar"
...
>>> dispatcher = Spam()
>>> method = getattr(dispatcher, "foo")
>>> method()
'bar'
If it's not contained within anything (...and it probably should be), then you can do something similar with locals():
>>> def foo():
...   return 42
...
>>> locals()["foo"]()
42
>>>
I'd say either option is better than using eval(), as then you can at least use hasattr() to check if something exists and is a callable before blindly trying to run it.
Duly noted, thank you. I'll give it a try.