How can I use the string in the list as string methods in python?

Viewed 52

I am trying to print some given string in three different ways provided by string methods which are inside a list as strings. Is there a way to convert those strings as methods to use it during loop iteration?

some_string = "hello people!"


string_operations = [".upper()", ".lower()", ".capitalize()"]
for methods in string_operations:
    print(some_string+methods)
2 Answers

In this case you can do something like:

some_string = "hello people!"
string_methods = [str.upper, str.lower, str.capitalize]
for method in string_methods:
    print(method(some_string))

If you have the methods as strings, you can do this:

some_string = "hello people!"

methods = ["upper", "lower", "capitalize"]
for method_str in methods:
    method = getattr(str, method_str)
    print(method(some_string))
Related