TransWikia.com

String formatting: optional section

Stack Overflow Asked by Cerno on February 3, 2021

I have the following string format:

string = "{part1}_{part2}_{part3}"

I want to format the string by setting the different parts to different values.
The catch is that part2 is optional. So I can’t do the following, because it would leave me with a duplicate underscore:

result = string.format(part1="A", part2="", part3="B")
actual_result = "A__B"
desired_result = "A_B"

I cannot replace all duplicate underscores by single ones afterwards because the strings I use to replace the parts may already contain duplicate underscores:

result = string.format(part1="A__A", part2="", part3="B__B")
result = result.replace("__", "_")
actual_result = "A_A_B_B"
desired_result = "A__A_B__B"

My solution looks like this, but I wonder if there is something more elegant.

ignore_str = "$IGNORE_STRING$"
string = "{part1}_{part2}_{part3}"

result = string.format(part1="A__A", part2=ignore_str, part3="B__B")    
result = result.replace("_" + ignore_str, "")
actual_result = "A__A_B__B"

I was kind of hoping that there was a cool str.format() trick I could apply. I know that I can write my own format classes but that seems to produce a lot more code and may become quite confusing for the reader.

I am looking for a solution that is pythonic, elegant and readable.

One Answer

This is a way to make the underscore optional in Python 3. :)

spacer = "_" if part2 else ""
desired_result = f"{part1}_{part2}{spacer}{part3}"

Answered by Vivian on February 3, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP