Sai Krishna
Sai Krishna

Reputation: 8187

How to convert two strings to give you a function name in Python

If you had two strings, like so ->

string1 = "get"  
string2 = "Feed"

So how would you use these 2 strings to call a function named -> getFeed() ?

Upvotes: 4

Views: 125

Answers (3)

Hyperboreus
Hyperboreus

Reputation: 32429

Assume the function is located inside foo. Then call

getattr(foo, string1 + string2) ()

Upvotes: 2

K Mehta
K Mehta

Reputation: 10543

If ImportedLib had your function getFeed(), you'd call it as such:

import ImportedLib
getattr(ImportedLib, string1+string2)()

Upvotes: 3

Jordan
Jordan

Reputation: 32522

Depending on where the function is, you can use one of these:

globals()[string1 + string2]()
locals()[string1 + string2]()

Upvotes: 7

Related Questions