如何将列表中的字符串用作 python 中的字符串方法?
How can I use the string in the list as string methods in python?
我正在尝试以三种不同的方式打印一些给定的字符串,这些方式由字符串方法提供,这些方式在列表中作为字符串。有没有办法将这些字符串转换为在循环迭代期间使用它的方法?
some_string = "hello people!"
string_operations = [".upper()", ".lower()", ".capitalize()"]
for methods in string_operations:
print(some_string+methods)
在这种情况下,您可以执行以下操作:
some_string = "hello people!"
string_methods = [str.upper, str.lower, str.capitalize]
for method in string_methods:
print(method(some_string))
如果你有字符串形式的方法,你可以这样做:
some_string = "hello people!"
methods = ["upper", "lower", "capitalize"]
for method_str in methods:
method = getattr(str, method_str)
print(method(some_string))
我正在尝试以三种不同的方式打印一些给定的字符串,这些方式由字符串方法提供,这些方式在列表中作为字符串。有没有办法将这些字符串转换为在循环迭代期间使用它的方法?
some_string = "hello people!"
string_operations = [".upper()", ".lower()", ".capitalize()"]
for methods in string_operations:
print(some_string+methods)
在这种情况下,您可以执行以下操作:
some_string = "hello people!"
string_methods = [str.upper, str.lower, str.capitalize]
for method in string_methods:
print(method(some_string))
如果你有字符串形式的方法,你可以这样做:
some_string = "hello people!"
methods = ["upper", "lower", "capitalize"]
for method_str in methods:
method = getattr(str, method_str)
print(method(some_string))