fmakawa
fmakawa

Reputation: 350

Converting string concatenation with lambda to f strings

I am trying to wrap my head around advanced usage of f strings in Python 3 and I can't seem to figure out their usage with lambda functions. For example, when you have string concatenation that uses lambda to define some of the values in the string how do you go about using f strings? Even more so when one of the values uses an if function to define the value.

For example, I have tried the following:

        cmd_out = reduce(lambda acc, x: f'{acc} -v {x["Source"]}:{x["Destination"]}'
                         f'{(":ro" if not x["RW"] is True else " ")} {mounts}')

But this doesn't work.

This is the original with concatenation.

cmd_out = reduce(lambda acc,x: acc + "-v " + x["Source"] + ":" + x["Destination"]+ (":ro" if not x["RW"] is True else "") + " ", mounts, "")

So rather than using the concatation I would like to be able to use f strings to simplify the process and reduce errors. Any thoughts?

Upvotes: 1

Views: 1864

Answers (1)

chepner
chepner

Reputation: 531758

You are trying to include mounts in the lambda expression, but that's what reduce is supposed to iterate over. I wouldn't use reduce here; use the join method instead.

cmd_out = " ".join(f'-v {x["Source"]}:{x["Destination"]}{"" if x["RW"] else ":ro"}'
                   for x in mounts)

Upvotes: 1

Related Questions