zoukankan      html  css  js  c++  java
  • 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'>

    
    
  • 相关阅读:
    HTML5程序设计web workers API 学习笔记
    HTML5 拖拽API 学习笔记
    2013.03.23这天的一点感触和计划
    localStorage实现返回到原位置以及pjax的反思
    HTML5 localStorage浅谈
    javascript学习之函数对象简介
    display:-webkit-box
    由登录表单的用户体验细节说开
    前端和用户体验
    Laravel实践step1,一个简单的crud
  • 原文地址:https://www.cnblogs.com/bigdata-stone/p/10201610.html
Copyright © 2011-2022 走看看