[Python] F-string format for conditionally prefixing a value

Discussão em 'Python' iniciado por Stack, Outubro 2, 2024.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página