0

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

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

Comments

0
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

Comments

0

Evaluate it

try:
 eval(alignment.lower())(new_string)
except NameError:
 print 'Error'
answered Apr 3, 2013 at 14:00

1 Comment

Yeehaw! Let's input os.system then... and as new_string... let's take something arbitrary, such as rm -rf /, maybe...

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.