Is there a way to convert a string to a method in python? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 2

Is there a way to convert a string to a method in python?

string = 'eggs, Spam, and eggs' x = 'string.capitalize()' print (x) ? print(method(x)) I know I could just print (string.capitalize()) But I want to apply a bunch of different methods to different strings without having to type it over and over. a = 'casefold' x = 'string.' + a + '()' ?convert x to method type?

18th Oct 2017, 11:42 AM
Eric Sens
7 Respostas
+ 5
I mean, exec() and eval() could be used, but I suggest strongly against that as exec() and eval() will evaluate anything (such as mass file deletion). Maybe use a lambda expression instead: x = lambda x: x.capitalize() str = "hello" print(x(str)) Output: Hello
18th Oct 2017, 12:12 PM
LunarCoffee
LunarCoffee - avatar
+ 5
You need to be very very careful in any "real" code when using eval/exec, if there is any doubt or lack of control over the args being passed to those functions, in particular if user input is involved. This is a classic security concern... having your code execute arbitrary commands fed into it is a Bad Thing. So just make sure that eval is only operating on internally hard-coded arguments that you choose and understand.
18th Oct 2017, 1:43 PM
Erik
+ 2
What @Eric said. About that None, it's because the help() function is like a print() function, in that it prints the text to the screen. Because of that, the print() part of the: print(exec('help(str.' + x + ')')) line is not actually doing anything, and, as such, returns None. That line should be: exec('help(str.' + x + ')') instead, simply removing the print() function call.
18th Oct 2017, 2:06 PM
LunarCoffee
LunarCoffee - avatar
+ 2
Thank you both very much.
18th Oct 2017, 4:05 PM
Eric Sens
+ 2
Learn Lisp šŸ˜‚šŸ˜‚
20th Oct 2017, 7:18 AM
Chriptus13
Chriptus13 - avatar
+ 1
Thank you. I actually found eval() about two minutes before I got your reply. I believe that is what I was looking for. But could you expound on why you think I shouldn't use it? This is what I am working on. https://code.sololearn.com/c4nOCGaSSI13/?ref=app It is doing what I want, but I keep getting 'None' at the end of my output on one section.
18th Oct 2017, 12:31 PM
Eric Sens
+ 1
Thank you. I actually found eval() about two minutes before I got your reply. I believe that is what I was looking for. But could you expound on why you think I shouldn't use it? This is what I am working on. https://code.sololearn.com/c4nOCGaSSI13/?ref=app It is doing what I want, but I keep getting 'None' at the end of my output on one section.
18th Oct 2017, 12:32 PM
Eric Sens