Home > database >  How to write a function to format string in a clear way?
How to write a function to format string in a clear way?

Time:06-14

I'm sure that this can be written in a clear way, but I can't find any other way:

'The items included in the {} are exactly the same as the items in the {}.
 Do you want to proceed?'.format(
    'Box2' if request.data.get('box_type') == Box.BoxType.Box2 else 'Box3',
    'Box3' if request.data.get('box_type') == Box.BoxType.Box3 else 'Box2'
 )

CodePudding user response:

Maybe use variables? Also, it is advised to use f-strings:

first_box = "Box2" if request.data.get("box_type") == Box.BoxType.Box2 else "Box3"
second_box = "Box3" if request.data.get("box_type") == Box.BoxType.Box3 else "Box2"
print(f"The items included in the {first_box} are exactly the same as the items in the {second_box}. Do you want to proceed?")

CodePudding user response:

If you do this often in your script, I'd suggest using a global constant:

PROMPT = 'The items included in the {} are exactly the same as the items in the {}. Do you want to proceed?'

And then a helper:

def get_prompt(box_type):
    if box_type == Box.BoxType.Box2:
        return 'Box2', 'Box3'
    return 'Box3', 'Box2'

Then calling the helper:

box_type = request.data.get('box_type')
boxes = get_prompt(box_type)
print(PROMPT.format(*boxes))
  • Related