Python string format template for selected parameters

Question:

I want to create a string template that only selected parameters gets value in each session.

For example:

def format_fruits(fruits_num):

 s = "I have {fruits_num} and I like {fruit_name} very much"

 s.format(fruits_num=fruits_num, fruit_name='apple')
 s.format(fruits_num=fruits_num, fruit_name='orange')

I want to avoid the repeated assignment of fruits_num=fruits_num

In a pseduo code:

def format_fruits(fruits_num):

 s = "I have {fruits_num} and I like {fruit_name} very much".format(fruits_num=fruits_num)

 s.format(fruit_name='apple')
 s.format(fruit_name='orange')

I this possible? Thanks.

Asked By: dasdasd

||

Answers:

You can double the { around fruits_name so that it will be literal, which will keep it until the next call to .format().

def format_fruits(fruits_num):
    s = "I have {fruits_num} and I like {{fruit_name}} very much".format(fruits_num=fruits_num)
    print(s.format(fruit_name='apple'))
    print(s.format(fruit_name='orange'))
Answered By: Barmar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.