1. 程式人生 > >python函式之format()

python函式之format()

 直接上原始碼:

    def format(self, *args, **kwargs): # known special case of str.format
        """
        S.format(*args, **kwargs) -> str
        
        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces ('{' and '
}'). """ pass

 

    從上面的註釋中可以看到:

      (1)S.format()函式得到的是一個被格式化的字串,從變長引數args以及字典型變數kwargs來進行替換,替換額物件尅被識別為'{'和'}'

      (2)編碼實戰:

 #    a = '{1},{0}'.format('python',2018)
   # print(type(a))
# print(a)
執行結果:
 
 

    <class 'str'>
    2018,python


    # a ='
{},{}'.format('python',2018) # print(type(a)) #資料型別是字串 # print(a)
執行結果:  

    <class 'str'>
    python,2018

    # a = '{0},{1},{0}'.format('python',2018)
    # print('a的資料型別是:',type(a))
    # print(a)
執行結果:

    a的資料型別是: <class 'str'>
    python,2018,python

 
a =  '{name},{year}'.format(year=2018,name='python')
# print('a=',a)
# print('a的資料型別是:',type(a))
運算結果:
  
a= python,2018
a的資料型別是: <class 'str'>
 
 
 


#字典資料型別
dict_val ={'name':'java','age':28,'James Gaoslim':'builderman'}
print('資料型別',type(dict_val))
print(dict_val)
#對字典中的資料進行遍歷
for key in dict_val.keys():
print('{0},{1}'.format(key,type(key))) #打印出鍵值和鍵值的資料型別

# 接下來實現對value值進行訪問
for value in dict_val.values():
print('{0},{1}'.format(value,type(value)))
執行結果:
 
 

  {'name': 'java', 'age': 28, 'James Gaoslim': 'builderman'}
  name,<class 'str'>
  age,<class 'str'>
  James Gaoslim,<class 'str'>
  java,<class 'str'>
  28,<class 'int'>
  builderman,<class 'str'>

 
for item in dict_val.items():
print('{0},{1}'.format(item,type(item)))

#執行結果

'name', 'java'),<class 'tuple'>
('age', 28),<class 'tuple'>
('James Gaoslim', 'builderman'),<class 'tuple'>