+ 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?
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
+ 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.
+ 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.
+ 2
Thank you both very much.
+ 2
Learn Lisp 😂😂
+ 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.
+ 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.