What is the easiest or most elegant way to let the user input a list in a console program?
A list with the brackets and commas?
The easiest way is also taboo:
>>> eval(raw_input("Enter a list: ")) Enter a list: [1,2,3] [1, 2, 3]
IMO, eval() should almost never be used for the simple reason that it allows the user to type ANYTHING. As in
>>> eval(raw_input("Enter a list: ")) Enter a list: os.rmdir("C:\") OOPS.
which WILL execute if the appropriate permissions are there.
So instead, we have to do it by hand:
def get_list(): mylist = raw_input("Enter a list: ").strip() if mylist.startswith('['): mylist = mylist[1:] else: print "ERROR!" return None if mylist.endswith(']'): mylist = mylist[:-1] else: print "ERROR!" return None return mylist.split(",") >>> get_list() Enter a list: [1,2,3,4] ['1', '2', '3', '4']
But note: this will return strings!
A possible compromise might be this:
>>> def get_list2(): mylist = raw_input("Enter a list: ").strip() if not mylist.startswith('[') or not mylist.endswith(']'): print "ERROR!" return None return eval(mylist) >>> get_list2() Enter a list: [1,2,3,4] [1, 2, 3, 4] >>>
with the error checking in place, I think eval() is safe here.
Thanks Jeff, I am learning a lot. I will test drive your code and let you know.
Hey, so I wanna ask how I need to create a method who will remove word if in that word is 2 same chars. Example: "Potato" in this word there is a 2 "o" chars so this word will need to be removed. "Forum" in this word there is no ...
Hi I'm having a problem implementing a mini shopping cart drop down in the header to show the user all the products they have in their shopping cart. It seems the only solution for this is Ajax, and I've looked all over and can't find anything that I could possibly ...
Hi. Im using vb 2010. I want to dynamically add textboxes to my form by clicking on a button. I've google searched and so far this code worked:
Private Sub btn_addline_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_addline.Click Dim txtB1 As New TextBox Dim i For i = ...