Python Forum
How to run a method on an argument in a formatted string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to run a method on an argument in a formatted string
#1
class Test:

    def __init__(self):
        self.name = "unnamed"
        self.subj = "he"
        self.poss = "his"
        self.obj = "him"
        self.reflex = "himself"

    def quirks(self):
        return "{0.subj} is happy.".format(self)


test_NPC1 = Test()

print(test_NPC1.quirks())
Output:
he is happy. Process finished with exit code 0
I want to be able to run a method, like .capitalize(), on the string value passed into the placeholder in the formatted text above, but I'm not sure how to do it. If I place it after .format(self), it affects the entire string, which is not what I want. I want to apply it specifically to the string value that is passed in.
Reply
#2
The answer was f-strings. return f"{self.subj.capitalize()} is happy."
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  i want to use type= as a function/method keyword argument Skaperen 9 1,771 Nov-06-2022, 04:28 AM
Last Post: Skaperen
  Formatted string not translated by gettext YvanM 10 1,916 Sep-02-2022, 08:46 PM
Last Post: YvanM
  TypeError: float() argument must be a string or a number, not 'list' Anldra12 2 4,758 Jul-01-2022, 01:23 PM
Last Post: deanhystad
Question How to pass a method as argument in an another method? anilanvesh 6 2,663 Sep-30-2021, 10:18 PM
Last Post: deanhystad
  TypeError: int() argument must be a string, a bytes-like object or a number, not 'Non Anldra12 2 5,105 May-02-2021, 03:45 PM
Last Post: Anldra12
  return string from function with one argument jamie_01 2 2,144 May-28-2020, 11:07 PM
Last Post: menator01
  SyntaxError: positional argument follows keyword argument syd_jat 3 5,733 Mar-03-2020, 08:34 AM
Last Post: buran
  Python convert multi line into single line formatted string karthidec 2 9,272 Dec-23-2019, 12:46 PM
Last Post: karthidec
  How to Call a method of class having no argument dataplumber 7 6,314 Oct-31-2019, 01:52 PM
Last Post: dataplumber
  TypeError: int() argument must be a string or a number, not 'NoneType' Hadad 2 6,785 Jul-30-2019, 07:22 PM
Last Post: Hadad

Forum Jump:

User Panel Messages

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