Python Forum
remove apostrophes in list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: remove apostrophes in list (/thread-4080.html)



remove apostrophes in list - sparkz_alot - Jul-21-2017

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


RE: remove apostrophes in list - Bass - Jul-21-2017

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.


RE: remove apostrophes in list - nilamo - Jul-21-2017

But then they wouldn't be strings anymore, and it'd suddenly become invalid syntax. What are you REALLY trying to do? :p


RE: remove apostrophes in list - sparkz_alot - Jul-21-2017

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.


RE: remove apostrophes in list - nilamo - Jul-21-2017

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.


RE: remove apostrophes in list - sparkz_alot - Jul-21-2017

Duly noted, thank you. I'll give it a try.