Home > OS >  Python string format template for selected parameters
Python string format template for selected parameters

Time:08-08

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.

CodePudding user response:

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'))
  • Related