1

I want to create an f-string that combines two strings, prepending a '.' character to the second if it is not empty.

reference = "file"

modifier = "read"
print(f"unknown pattern")    # Should output "file.read" since modifier is not empty

modifier = ""
print(f"unknown modifier")    # Should output "file" (not "file.") since modifier is empty

Is there a dedicated syntax for this kind of conditional prefixing, similar to that used in twig?

I would like to avoid using str.join() or conditional statements if possible.

3
  • 3
    It might be easiest if you chain a call of .rstrip(".") to your f-string. Unless your modifier or reference ends with a dot... but that might not be your case? Commented Oct 2, 2024 at 5:23
  • 4
    '.'.join(s for s in (reference, modifier) if s)? Commented Oct 2, 2024 at 5:26
  • 1
    "similar to that used in twig" - I don't see it. Where did you show it? Commented Oct 2, 2024 at 8:31

5 Answers 5

2

From what I understand, you are combining two strings with a dot between them, and if the second string is blank, you don't want to add the dot. In that case, you can add the dot regardless and then remove it if it's at the end of the combined string. However, keep in mind that if your first string or the second already has a dot at the end, this approach may not work as intended.

reference = "file"
modifier = "read"

result = f"{reference}.{modifier}".rstrip('.')
Sign up to request clarification or add additional context in comments.

Comments

1

You can use almost any Python expression between brace pairs, so it is certainly possible, even though an f-string might in the end not be the most elegant way to do it.

If we consider the f-string where the dot would always be included:

f"{reference}.{modifier}"

...then we need to adapt it to make the dot conditional. To achieve that, the dot could appear in a brace pair, where we are free to embed it inside some Python expression. For instance, we could do this:

f"{reference}{'.'[not modifier:]}{modifier}"

not modifier is a boolean, but also an integer, which is either 0 or 1. It serves here to slice the string '.' to either '.' or '' depending on that integer.

Another example: we could use the and operator and its short-circuit behavior to produce the '.' or just '':

f"{reference}{modifier and '.'}{modifier}"

Here the and operator evaluates to the second operand (i.e. the dot) when modifier is truthy (i.e. it is not empty). When this is not the case, it evaluates to the first operand, which then is the empty string.

Comments

0

I don't know if you can do it without conditional statements. Here it is with a one-liner conditional statement at least.

reference = "file"
modifier = "read"

fstring = f"{reference}.{modifier}" if modifier != "" else reference

1 Comment

The question is "...create an f-string that combines two strings". This does not answer that question
0

Sadly, it looks indeed, like the Python Format Specification Mini-Language doesn't provide for strings as many format options, as for numbers.

The closest in similarity to a format string usage-wise

that I've been able to come up with (the value is named once only and everything fits in one line) – yet with the conditional –, is a lambda expression with – analogous to other answers – a ternary evaluation, which – unlike a boolean expression – has the benefit of working with both, empty strings and NoneType values.


f"{reference}{(lambda x: f'.{x}' if x else '')(modifier)}"

Maybe at some point, the Format Language can be extended to accomodate something like

f"{value:'prefix'?s}"

and

f"{value:?s'suffix'}"

Which would prepend or append a string only when the value is actually available to prepend or append to. That would be a much simpler notation and sweet as sugar.

Comments

-1

I think you should make this:

def funk(reference, modifer=""):
    if modifer != "":
        return f"{reference}.{modifer}"
    else:
        return "unkown modifer"
reference = "file"
modifer = "read"
funk(reference) # output: unkown modifer
funk(reference, modifer) # output: file.read

In funk you can make easier:

def funk(reference, modifer=""):
    return f"{reference}.{modifer}" if modifer != "" else "unkown modifer")

I hope I helped you.

2 Comments

The question is "...create an f-string that combines two strings". This does not answer that question
You can't replace the print with return???

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.