4 ms·
greeting = "hello {}" greet = partial(str.format, greeting) greet("world") How would you pass a variable format string to f"" ?
by linkdd 6y ago
greeting = "hello {}"
greet = partial(str.format, greeting)
greet("world")
How would you pass a variable format string to f"" ?
- pletnes 6y agoOr read the string to be formatted from a file, to name another use case.
- eljost 6y agoYou can use variables in the formats. >>> flt = 1.2345 >>> two = 2 >>> f"{flt:.{two}f}" '1.23'
- thaumasiotes 6y agoThat is the opposite of the problem being posed. The question is how you define `greet` using f-strings.
- sumzup 6y agogreet = lambda x: f"hello {x}"
- thaumasiotes 6y agoWhy is the example greet = partial(str.format, greeting) greet("world") as opposed to just greeting.format("world") ?
- contravariant 6y agoThe real question is why they didn't just write: greet = greeting.format
- linkdd 6y agoIt was implying you could use the str.format function as argument to other computations, something you cannot do with f-strings.
- nokko 6y agoI mean, if you're comfortable with `functools.partial`, lambdas are no great stretch: greet_fstring = partial(lambda _,s: f"hello {s}", greeting)
- sumzup 6y agogreet = lambda x: f"hello {x}"
- linkdd 6y agoWhat 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
- staticassertion 6y agoSomething along the lines of... code = 'f"{input()} {x}"' lambda x: eval(code) (Please don't do this)
- linkdd 6y agoYes, I'll stick to using str.format :)
- staticassertion 6y agocode = 'f"here it is {eval(input())}"' (lambda: eval(code))() k, there we go
- AlphaSite 6y agoYou can’t use f-strings for that.
- linkdd 6y agoThat was exactly my point.
- klyrs 6y agoThat isn't the purpose for f-strings. You still have % and .format