如何在Python中将列表中的字符串用作字符串方法?

3
我试图使用字符串方法在一个包含三个不同字符串的列表中以三种不同的方式打印给定的字符串。是否有办法将这些字符串转换为方法以便在循环迭代期间使用?
some_string = "hello people!"


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

1
在这种情况下,您可以做如下操作:

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

1
如果您有方法的字符串,可以这样做:
some_string = "hello people!"

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接