-1

The following codes -

d = {'name':'Joe',
     'age': 25
    }

mypara ='''
My name is {name}.
   - I am {age} year old.
'''

print(mypara.format(**d))

gives the following output:

My name is Joe.
   - I am 25 year old.

How can I get output like below:

My name is {Joe}.
   - I am {25} year old.

The following works, but I'm looking for using the dictionary instead of variables -

name = 'Joe'
age = 25

mypara = f'''
My name is {{name}}.
   - I am {{age}} year old.
'''

print(mypara)

Output:

My name is {Joe}.
   I am {52} year old.
Rafiq
  • 820
  • 1
  • 11
  • 19
  • Why the multiline string? Do you want your second line of output to be indented? – AMC Nov 08 '19 at 05:48
  • I need multiple lines, and yes, indentation is also needed. You may not see this is important for this question, but I just placed here to show my style of output I need. Someone may answer with just a single line, someone may give a solution that cannot indent. – Rafiq Nov 08 '19 at 06:08
  • Can you rephrase the last sentence of your comment, i’m not sure what you mean. I’m sorry that my solution ended up being a bit verbose, I just don’t know if there is much I can do. – AMC Nov 08 '19 at 06:11

1 Answers1

1

This works:

d = {'name':'Joe', 'age': 25}

my_para = f'''
My name is {{{d['name']}}}.
   - I am {{{d['age']}}} years old.
'''

print(my_para)

Is there any reason why you’re using a multiline string?

AMC
  • 2,466
  • 7
  • 11
  • 31
  • Yes, I need to get output of dozens of lines of texts. I definitely can use this, but it's not that clean. Too many brackets and braces. When I will write dozens of lines of texts, it will be unmanageable. – Rafiq Nov 08 '19 at 05:56
  • 1
    What do you mean “I need to get output of dozens of lines of texts.”? And check my comment on your post, about whether you want to indent your second line or not. Personally I think it’s absolutely usable, although it would be nice if you could provide more of your code so that we can potentially find a better solution. – AMC Nov 08 '19 at 05:59
  • Sorry forgot to mention you @Rafiq – AMC Nov 08 '19 at 06:03