📜  Python String format_map() 方法

📅  最后修改于: 2022-05-13 01:54:27.562000             🧑  作者: Mango

Python String format_map() 方法

Python字符串 format_map()方法是Python中的内置函数,用于返回字典键的值。

示例 1: Python字符串 format_map() 方法

Python3
# input stored in variable a.
a = {'x':'John', 'y':'Wick'}
  
# Use of format_map() function
print("{x}'s last name is {y}".format_map(a))


Python3
# input stored in variable a.
a = {'x':"geeksforgeeks", 'y':'b'}
  
# Use of format_map() function
print('{x} {y}'.format_map(a))


Python3
# Input dictionary
profession = { 'name':['Barry', 'Bruce'],
               'profession':['Engineer', 'Doctor'],
               'age':[30, 31] }
                       
# Use of format_map() function 
print('{name[0]} is an {profession[0]} and he'
      ' is {age[0]} years old.'.format_map(profession))
        
print('{name[1]} is an {profession[1]} and he'
      ' is {age[1]} years old.'.format_map(profession))


Python3
# Python code showing practical 
# use of format_map() function
def chk_msg(n):
          
    # input stored in variable a.
    a = {'name':"George", 'mesg':n}
      
    # use of format_map() function 
    print('{name} has {mesg} new messages'.format_map(a))
  
chk_msg(10)


输出:

John's last name is Wick

示例 2:

Python3

# input stored in variable a.
a = {'x':"geeksforgeeks", 'y':'b'}
  
# Use of format_map() function
print('{x} {y}'.format_map(a))

输出:

geeksforgeeks b

示例 3:

Python3

# Input dictionary
profession = { 'name':['Barry', 'Bruce'],
               'profession':['Engineer', 'Doctor'],
               'age':[30, 31] }
                       
# Use of format_map() function 
print('{name[0]} is an {profession[0]} and he'
      ' is {age[0]} years old.'.format_map(profession))
        
print('{name[1]} is an {profession[1]} and he'
      ' is {age[1]} years old.'.format_map(profession))

输出:

Barry is an Engineer and he is 30 years old.
Bruce is an Doctor and he is 31 years old.

示例 4:实际应用

format_map()函数可用于任何实际应用。

Python3

# Python code showing practical 
# use of format_map() function
def chk_msg(n):
          
    # input stored in variable a.
    a = {'name':"George", 'mesg':n}
      
    # use of format_map() function 
    print('{name} has {mesg} new messages'.format_map(a))
  
chk_msg(10)

输出:

George has 10 new messages