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
  How can I write formatted (i.e. bold, italic, change font size, etc.) text to a file? JohnJSal 12 28,118 Feb-13-2025, 04:48 AM
Last Post: tomhansky
  Destructor method adding in string chizzy101010 3 929 Sep-03-2024, 12:31 PM
Last Post: chizzy101010
  comtypes: how to provinde a list of string to a COM method zalanthas 0 950 Jun-26-2024, 01:27 PM
Last Post: zalanthas
  i want to use type= as a function/method keyword argument Skaperen 9 3,604 Nov-06-2022, 04:28 AM
Last Post: Skaperen
  Formatted string not translated by gettext YvanM 10 3,914 Sep-02-2022, 08:46 PM
Last Post: YvanM
  TypeError: float() argument must be a string or a number, not 'list' Anldra12 2 6,729 Jul-01-2022, 01:23 PM
Last Post: deanhystad
Question How to pass a method as argument in an another method? anilanvesh 6 4,055 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 7,574 May-02-2021, 03:45 PM
Last Post: Anldra12
  return string from function with one argument jamie_01 2 2,962 May-28-2020, 11:07 PM
Last Post: menator01
  SyntaxError: positional argument follows keyword argument syd_jat 3 7,542 Mar-03-2020, 08:34 AM
Last Post: buran

Forum Jump:

User Panel Messages

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