Python Forum
Passing string functions as arguments
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Passing string functions as arguments
#1
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
Reply
#2
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)
Clunk_Head likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
I knew it was something simple.
Thanks a bunch
Reply
#4
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))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Passing writable arguments to functions. Assembler 11 825 Jan-15-2024, 11:32 PM
Last Post: sgrey
  TypeError: not enough arguments for format string MaartenRo 6 2,864 Jan-09-2022, 06:46 PM
Last Post: ibreeden
  Why Pass Functions as arguments? muzikman 14 5,525 Jan-18-2021, 12:08 PM
Last Post: Serafim
  redirect url_for passing arguments with the url Leon79 1 1,612 Jul-09-2020, 05:20 PM
Last Post: Leon79
  passing-arguments-from-one-script-to-another jacklee26 7 3,160 Apr-21-2020, 03:55 PM
Last Post: deanhystad
  Python 2.7 passing variables from functions zetto33 1 1,754 Mar-19-2020, 07:27 PM
Last Post: Larz60+
  MySQLdb._exceptions.ProgrammingError: not enough arguments for format string. farah97 0 3,303 Jan-22-2020, 03:49 AM
Last Post: farah97
  Accepting strings as arguments when slicing a string? (Ziyad Yehia on Udemy) Drone4four 4 3,725 Aug-23-2019, 07:59 PM
Last Post: Drone4four
  TypeError: not all arguments converted during string formatting RedSkeleton007 1 14,909 Jul-15-2018, 08:51 PM
Last Post: ichabod801
  Still confused about how passing arguments works RedSkeleton007 3 2,916 Apr-25-2018, 11:01 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020