Cerno
Cerno

Reputation: 831

String formatting: optional section

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.

Upvotes: 2

Views: 551

Answers (1)

Vivian
Vivian

Reputation: 355

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

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

Upvotes: 1

Related Questions