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

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.

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.

Comments

0

Evaluate it

try:
    eval(alignment.lower())(new_string)
except NameError:
    print 'Error'

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

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.