Pepv
Pepv

Reputation: 171

Apply same format on multiple string variables

I'm coding a menu. Options 1,2 and 3 will populate project. Options 4, 5 and 6 depend on the value of project. I want to strikethrough options 4,5 and 6 if project == None.

project = None
menuOptions = {0 : 'Option4', 1 : 'Option5', 2 : 'Option6'}

print("""
Choose:

━━━━━━━━━━━━ Text ━━━━━━━━━━━━
1 : Option1 
2 : Option2
3 : Option3

━━━━━━━━━━━━ Text ━━━━━━━━━━━━
4 : {0}

━━━━━━━━━━━━ Text ━━━━━━━━━━━━
5 : {1}

━━━━━━━━━━━━ Text ━━━━━━━━━━━━
6 : {2}     

    
0 : Exit""".format('\u0336'.join(menuOptions[0]) + '\u0336' if project == None else menuOptions[0],
                   '\u0336'.join(menuOptions[1]) + '\u0336' if project == None else menuOptions[1],
                   '\u0336'.join(menuOptions[2]) + '\u0336' if project == None else menuOptions[2]))

The code above works fine, but I'm wondering if there is a way of reducing the necessary code following this idea:

format( 
    for opt in menuOptions: 
        '\u0336'.join(menuOptions[opt]) + '\u0336' if project == None else menuOptions[opt]
)

The objective is to be able to add new elements into menuOptions, show them in the menu and apply the same formatting without having to "hardcode" it.

Upvotes: 0

Views: 45

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148890

You can use a starred comprehension here:

"""...""".format(*('\u0336'.join(opt) + '\u0336' if project is None else opt
                   for opt in menuOptions))

Upvotes: 1

Kris
Kris

Reputation: 589

So not sure if this is what you wanted, but you can reduce the "hardcording" a bit by doing this:

# list comprehension to get format options 
# (you can use a loop here instead for more readability if needed)
x = ['\u0336'.join(menuOptions[opt]) + '\u0336' if project == None else menuOptions[opt] for opt in menuOptions]

print("""
Choose:

━━━━━━━━━━━━ Text ━━━━━━━━━━━━
1 : Option1 
2 : Option2
3 : Option3

━━━━━━━━━━━━ Text ━━━━━━━━━━━━
4 : {0}

━━━━━━━━━━━━ Text ━━━━━━━━━━━━
5 : {1}

━━━━━━━━━━━━ Text ━━━━━━━━━━━━
6 : {2} 

    
0 : Exit""".format(*x))

The * operator unpacks the list for you.

Upvotes: 1

Related Questions