1

I want to call a string's lower method from within the template string. This would ideally look something like

string = "Lowercase: {value.lower()}"

string.format(value=...)

However, this gives me an error saying AttributeError: 'str' object has no attribute 'lower()' (I understand why I'm getting this error).

I'm wondering if there's a way to achieve this. I've looked at using conversion (like '{value!r} for calling repr) but that didn't fix my problem. Could I create a custom conversion specifier?

(For the record, string.format(value=value.lower()) will not necessarily work in my case.)

2
  • 2
    Did you mean to use an f-string? Note the "f" prefix: f"Lowercase: {value.lower()}" Commented Oct 12, 2019 at 21:10
  • No, value is going to be a keyword passed into string.format(...), not necessarily a variable on its own. Commented Oct 12, 2019 at 21:19

2 Answers 2

3

IIRC, the format specification mini-language can access attributes of objects, but it can't call methods. It assumes you're looking for an attribute with the name "lower()", parentheses included.

Does value have to be a string? Perhaps you could create a string subclass with a @property that returns a lowercased version of itself. For example:

class StringEx(str):
    @property
    def lowercase(self):
        return self.lower()

x = StringEx("Hello, World!")
s = "Lowercase: {value.lowercase}"
print(s.format(value=x))

Result:

Lowercase: hello, world!

If you expect to have a lot of different format strings and don't want to implement a property for each string method, you can cover all the zero-argument methods in one go by overriding __getattr__:

class StringEx(str):
    def __getattr__(self, name):
        if name.endswith("()"):
            return getattr(self, name[:-2])()
        else:
            raise AttributeError

x = StringEx("HeLlO, WoRlD!")
format_strings = [
    "Regular: {value}",
    "Lowercase: {value.lower()}",
    "Uppercase: {value.upper()}",
    "Title: {value.title()}"
]

for s in format_strings:
    print(s.format(value=x))

Result:

Regular: HeLlO, WoRlD!
Lowercase: hello, world!
Uppercase: HELLO, WORLD!
Title: Hello, World!
Sign up to request clarification or add additional context in comments.

Comments

0

Just use f-str, this will help.

value = "HELLO world"
f"Lowercase: {value.lower()}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.