Re:Pattern matching accepted for Python
by linkdd on Tuesday February 09, 2021 @04:40PM
(#26082695)
How would you pass a variable format string to f"" ?
[ Parent
| on HN ]
You can use variables in the formats.
>>> flt = 1.2345
>>> two = 2
>>> f"{flt:.{two}f}"
'1.23'
Re:Pattern matching accepted for Python
by thaumasiotes on Tuesday February 09, 2021 @04:58PM
(#26082909)
That is the opposite of the problem being posed. The question is how you define `greet` using f-strings.
greet = lambda x: f"hello {x}" greet = lambda x: f"hello {x}"What if "hello {x}" is not a static string but was read from somewhere else?
Surely this would not work:
greeting = "hello {x}"
greet = lambda x: f greeting
Re:Pattern matching accepted for Python
by staticassertion on Tuesday February 09, 2021 @06:14PM
(#26083802)
Something along the lines of...
code = 'f"{input()} {x}"'
lambda x: eval(code)
(Please don't do this)
Re:Pattern matching accepted for Python
by staticassertion on Tuesday February 09, 2021 @11:36PM
(#26085783)
code = 'f"here it is {eval(input())}"'
(lambda: eval(code))()
k, there we goYes, I'll stick to using str.format :)
Re:Pattern matching accepted for Python
by klyrs on Wednesday February 10, 2021 @01:33AM
(#26086230)
That isn't the purpose for f-strings. You still have % and .format
Re:Pattern matching accepted for Python
by AlphaSite on Tuesday February 09, 2021 @08:28PM
(#26084809)
You can’t use f-strings for that.
That was exactly my point.
I mean, if you're comfortable with `functools.partial`, lambdas are no great stretch:
greet_fstring = partial(lambda _,s: f"hello {s}", greeting)
Re:Pattern matching accepted for Python
by thaumasiotes on Tuesday February 09, 2021 @04:58PM
(#26082915)
Why is the example
greet = partial(str.format, greeting)
greet("world")
as opposed to just greeting.format("world")
?
Re:Pattern matching accepted for Python
by contravariant on Tuesday February 09, 2021 @06:02PM
(#26083678)
The real question is why they didn't just write:
greet = greeting.formatIt was implying you could use the str.format function as argument to other computations, something you cannot do with f-strings.