當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python String format_map()用法及代碼示例


format_map()函數是Python中的內置函數,用於返回字典鍵的值。

用法:

string.format_map(z)

z是存儲輸入字典的變量,而string是輸入字典的鍵。


參數:

input_dict:Takes a single parameter which is input dictionary.

返回值:

Returns key's values of the input dictionary.


代碼1:

# 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))

輸出:

John's last name is Wick


代碼2:

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

輸出:

geeksforgeeks b


代碼3:

# 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.


應用:
format_map()函數可以在許多實際應用中使用。

# 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


相關用法


注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 Python String | format_map()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。