Python%20Interview%20Questions%20and%20Answers
Question: How do I use strings to call functions/methods in Python?Answer:There are various techniques. * The best is to use a dictionary that maps strings to functions. The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct:
Note that getattr() works on any object, including classes, class instances, modules, and so on. This is used in several places in the standard library, like this:
Note: Using eval() is slow and dangerous. If you don't have absolute control over the contents of the string, someone could pass a string that resulted in an arbitrary function being executed. Is there an equivalent to Perl's chomp() for removing trailing newlines from strings? For simple input parsing, the easiest approach is usually to split the line into whitespace-delimited words using the split() method of string objects and then convert decimal strings to numeric values using int() or float(). split() supports an optional "sep" parameter which is useful if the line uses something other than whitespace as a separator. For more complicated input parsing, regular expressions more powerful than C's sscanf() and better suited for the task. |
Most helpful rated by users:
- What is Python?
- How do I share global variables across modules?
- How do you set a global variable in a function in Python?
- Why can\'t I use an assignment in an expression?
- What are the rules for local and global variables in Python?