0

How can we give arguments in a string containing '{}'? Example: string = "my age is '{}' years old'. We can print output by -> print(string.format(23)) so, output will be as -> my age is 23 years old.

I'm quessing is that when we have multiple '{}' in a string we have to send multiple arguments to '{}' the arguments are in a list or a tuple like (1, 2,3). How can we apply .format() to this?

I have this doubt while solving this problem -> question: I am 12 years 3 months 8 days old to required output: I am 3 years 8 months 12 days old. (Numbers should be in sorted form).

  • `'i have {} fingers, {} nose, and {} arms'.format(*(1,2,3))` – wwii Mar 17 '22 at 22:17
  • @wwii: That's overly complicated. This is simpler: `'i have {} fingers, {} nose, and {} arms'.format(1,2,3)` – martineau Mar 17 '22 at 22:21
  • 1
    [What does ** (double star/asterisk) and * (star/asterisk) do for parameters?](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters) – wwii Mar 17 '22 at 22:26
  • @martineau - They were asking how to use a tuple with str.format, at least that's how I read it. – wwii Mar 17 '22 at 22:42
  • @wwii: You're right, my mistake — sorry. – martineau Mar 17 '22 at 22:45
  • Related: [How to pass a dictionary into str.format()](https://stackoverflow.com/questions/6487501/python-3-2-how-to-pass-a-dictionary-into-str-format) – Stef Mar 18 '22 at 09:30

1 Answers1

0
string = "I am {} years {} months {} days old".format((12),(3),(8))

OR

string = "I am {} years {} months {} days old".format(*(12,3,8))
Stef
  • 13,242
  • 2
  • 17
  • 28
  • 3
    Please format the code - select it and type `ctrl-k`. .. [Formatting help](https://stackoverflow.com/editing-help)... [Formatting sandbox](https://meta.stackexchange.com/questions/3122/formatting-sandbox) – wwii Mar 17 '22 at 22:28
  • 1
    Alternatively `"I am {y} years {m} months {d} days old".format(y=12, m=3, d=8)` or `"I am {y} years {m} months {d} days old".format(**{'y':12, 'm':3, 'd':8})`. – Stef Mar 18 '22 at 09:26