In this program I am using a a user input to select which alignment the user wnats to align some text, at present I'm usinf if statements like so...
if alignment == "Left":
line = left(new_string)
elif alignment == "Right":
line = right(new_string)
elif alignment == "Centre":
line = centre(new_string)
elif alignment == "Fully":
line = fully(new_string)
else:
print "Error."
However, is there a a way that i can get rid of these statements and just use the users input to call either the left, right, centre, fully functions.
Thanks JT
waitingkuo
94.6k28 gold badges119 silver badges122 bronze badges
asked Apr 3, 2013 at 13:56
jtaylor94
1372 gold badges2 silver badges7 bronze badges
3 Answers 3
Map the alignment string to functions with a dictionary:
alignments = {'Left': left, 'Right': right, 'Centre', centre, 'Fully': fully}
try:
line = alignments[alignment](new_string)
except KeyError:
print "Error."
Python functions are first-class objects, so you can just store them as values in a dictionary.
answered Apr 3, 2013 at 13:57
Martijn Pieters
1.1m326 gold badges4.2k silver badges3.4k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
func = globals().get(alignment.lower())
if not func:
func = locals().get(alignment.lower())
func(new_string)
You should make sure that func is not None at the time it is called.
answered Apr 3, 2013 at 13:57
Niklas R
17k30 gold badges113 silver badges212 bronze badges
Comments
Evaluate it
try:
eval(alignment.lower())(new_string)
except NameError:
print 'Error'
answered Apr 3, 2013 at 14:00
waitingkuo
94.6k28 gold badges119 silver badges122 bronze badges
1 Comment
glglgl
Yeehaw! Let's input
os.system then... and as new_string... let's take something arbitrary, such as rm -rf /, maybe...lang-py