简体   繁体   中英

How can I print curly braces with this style formatted text in python

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.

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?

You can directly assign from dictionary:

d = {'name':'Joe',
     'age': 25
    }
mypara ='''
My name is {'''+ str(d['name'])+'''}.
   - I am {''' + str(d['age']) + '''} year old.
'''
print mypara

Output :

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

Hope this answers your question!!!

Have replace to do the typing for you.

Notice this code contains no f strings.

Write your string as:

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

Then use:

mypara = mypara.replace('{','{{{').replace('}','}}}') 

This can be made simultaneous rather than sequential with re.sub and the exact replacement might be made more specific depending on the input.

To produce:

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

Then when it is formatted via:

mypara = mypara.format(name='Bob', age=45)

The result is:

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

Try this:

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

mypara ='''
My name is {%(name)s}.
   - I am {%(age)s} year old.
'''

print(mypara % d)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM