How to make f-string dictionary format in python 3.6?

How can I make this format using python 3.6 F-String?

person = {'name': 'Jenne', 'age': 23}

print('My name {0[name]} and my age {1[age]}'.format(person, person))
print('My name {0} and my age {1}'.format(person['name'], person['age']))
+13
source share
6 answers

Well, you need a quote for the dictionary key.

f'My name {person["name"]} and my age {person["age"]}'

+17
source

Depending on the number of contributions your dictionary has made to a given string, you can use it .format(**dict)instead to make it more readable, even if it does not have the clear elegance of the string f.

>>> person = {'name': 'Jenne', 'age': 23}
>>> print('My name is {name} and my age is {age}.'.format(**person))

My name is Jenne and my age is 23.

While this option is situational, you may like to avoid harsh quotes and double quotes.

+10
source

Python 3.6 :

  1. print(f'My name {person["name"]} and my age {person["age"]}')
  2. print(f"My name {person['name']} and my age {person['age']}")

, ' " , .

+2

.

f'My name {person["name"]} and my age {person["age"]}'

name obj, f'name is {obj[name]}', dict, , f'name is {person["name"]}'.

+1

: f-stings. .

pkuphy ​​, :

f'My name {person["name"]} and my age {person["age"]}'

str.format() -:

>>> person = {'name': 'Jenne', 'age': 23}
>>> print('My name is {person[name]} and my age is {person[age]}.'.format(person=person))

My name is Jenne and my age is 23.

person , - .

+1

, , . .

person0 = {'name': 'Jenne', 'age': 23}
person1 = {'name': 'Jake', 'age': 29}
person2 = {'name': 'John', 'age': 31}
places = ['Naples', 'Marrakech', 'Cape Town']

print('''My name {0[name]} and my age {0[age]}, 
your name {1[name]} and your age {1[age]}, 
my favourite place {3[0]}'''.format(person0, person1, person2, places))

,

print('{2}'.format(person0, person1, person2, places))

, :

print('{3.__class__.__name__}'.format(person0, person1, person2, places))
0
source

Source: https://habr.com/ru/post/1675121/


All Articles