Python Forum

Full Version: Passing string functions as arguments
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to pass string functions like string.upper into another function as a parameter, there to be called as a function.
A simplified example:
def transform_nth(str_in, n, transform):
    return ''.join([str_in[:n], str_in[n].transform(), str_in[n + 1:]])

name = transform_nth("dave", 2, String.upper)
print(name)
Error:
Traceback (most recent call last): File "C:/Users/Documents/python/aaa.py", line 22, in <module> name = transform_nth("dave", 2, String.upper) NameError: name 'String' is not defined
def transform_nth(str_in, n, transform):
    return ''.join([str_in[:n], transform(str_in[n]), str_in[n + 1:]])
 
name = transform_nth("dave", 2, str.upper)
print(name)
I knew it was something simple.
Thanks a bunch
One can make it a little more robust by using [n:n+1] instead of [n], in case the string is too short. Also it is an opportunity to use functools.partial
from functools import partial

def transform_nth(func, str_in, n=0):
    return ''.join([str_in[:n], func(str_in[n:n+1]), str_in[n+1:]])

upper_nth = partial(transform_nth, str.upper)

print(upper_nth('dave', 3))