3 ms·
Yeah, this is the biggest reason why I'm excited about 3.6. I'm still using % for all formatting because .format() is so ugly and verbose, but I'll switch to f-
by amyjess 10y ago
Yeah, this is the biggest reason why I'm excited about 3.6. I'm still using % for all formatting because .format() is so ugly and verbose, but I'll switch to f-strings when I actually get the opportunity to use 3.6. In fact, when the PEP first appeared I immediately decided that from now on, I'd write all greenfield projects in Python 3 just so I can take advantage of f-strings as soon as I can use 3.6 (yes, this of all things was what made me switch from 2 to 3).
Though I think it would be cool if you could have a deferred format string, like so:
template = 'My name is {name} and I am {age} years old. Next year I will be {age + 1}!'
name = 'Amy'
age = 32
formatted = template.apply()
# formatted = 'My name is Amy and I am 32 years old. Next year I will be 33!'
So that way you could store the template as a constant somewhere and apply it after receiving input from the source of your choice.
You can kind of do that with [0], but it doesn't evaluate expressions (so the age + 1 thing won't work).
[0] .format(**locals()) # putting it here because HN eats the asterisks if it's not indented
- bastawhiz 10y agoYou can always put your f-string in a lambda if you don't want to evaluate it immediately. Pulling values from the scope of the function you call your apply() method from, though, is some scary magic. I wouldn't be confident that I hadn't screwed that up.
- spraak 10y agoWhat about.. def template(name, age): return f"My name is {name} and I am {age} .." formatted = template('Amy', 32) ? [Edit: I only started learning Python recently, and this is how I'd think of doing it come from JS: const template = (name, age) => `My name is ${name} and I am ${age}`; const formatted = template('Amy', 32); ]
- mixmastamyk 10y agoCheck string.Template from the docs.
- mixmastamyk 10y agoCool. string.Template might be what you are looking for.
- bluecalm 10y agoYeah, using templates like that is something you can do with format (and then just do template.format(arg_name1 = something1, arg_name2 = something2) and it seems like usecase important enough to not use f-string exclusively.