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'>


 

posted @ 2018-12-31 11:09  stone1234567890  阅读(630)  评论(0编辑  收藏  举报