Python Forum
trying to learn f-strings - puzzled by format() protocol
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
trying to learn f-strings - puzzled by format() protocol
#4
It's formatted one time. Here the proof of it:

# explaining with code
class MyFormat(str):
    def __format__(self, fmt_str):
        print('Magic method __format__ was called.')
        fmt_str = fmt_str.strip()
        if 'UPPER' == fmt_str:
            return self.upper()
        elif 'LOWER' == fmt_str:
            return self.lower()
        else:
            return self




my_str = MyFormat('Hello World')

# 3 calls, 3 times formatting
print(f'{my_str: UPPER }')
print(f'{my_str: LOWER }')
print(f'{my_str}')


# the same with the format method
# 3 calls, 3 times formatting
print('{:UPPER}'.format(my_str))
print('{:LOWER }'.format(my_str))
print('{}'.format(my_str))
Output:
Magic method __format__ was called. HELLO WORLD Magic method __format__ was called. hello world Magic method __format__ was called. Hello World Magic method __format__ was called. HELLO WORLD Magic method __format__ was called. hello world Magic method __format__ was called. Hello World
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: trying to learn f-strings - puzzled by format() protocol - by DeaD_EyE - Jul-25-2019, 12:28 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  print a list strings is fast but printing the joined strings is slow Skaperen 9 3,957 Aug-26-2019, 07:48 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

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