Monday, 25 August 2025

TIL Python: f"hello {thing!r}"

 When formatting strings in Python, you can use a suffix to run a conversion on it:

Three conversion flags are currently supported: '!s' which calls str() on the value, '!r' which calls repr() and '!a' which calls ascii().

Some examples:

"Harold's a clever {0!s}"        # Calls str() on the argument first
"Bring out the holy {name!r}"    # Calls repr() on the argument first
"More {!a}"                      # Calls ascii() on the argument first

 I ran into it while reading tiktoken/core.py:

    def __repr__(self) -> str:

        return f"<Encoding {self.name!r}>"

No comments:

Post a Comment