• 技术文章 >常见问题 >Python常见问题

    python的format函数怎么用

    silencementsilencement2019-12-21 10:21:39原创20396

    Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

    python学习网,大量的免费python视频教程,欢迎在线学习!

    基本语法是通过 {} 和 : 来代替以前的 % 。

    format 函数可以接受不限个参数,位置可以不按顺序。

    例如

    >>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
    'hello world'
     
    >>> "{0} {1}".format("hello", "world")  # 设置指定位置
    'hello world'
     
    >>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
    'world hello world'

    也可设置参数

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    print("网站名:{name}, 地址 {url}".format(name="python学习网", url="www.py.cn"))
     
    # 通过字典设置参数
    site = {"name": "python学习网", "url": "www.py.cn"}
    print("网站名:{name}, 地址 {url}".format(**site))
     
    # 通过列表索引设置参数
    my_list = ['python学习网', 'www.py.cn']
    print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的

    输出结果

    网站名:python学习网, 地址 www.py.cn
    网站名:python学习网, 地址 www.py.cn
    网站名:python学习网, 地址 www.py.cn
    专题推荐:format
    品易云
    上一篇:python的import语句怎么用 下一篇:python写文件有时候写不进去怎么办

    相关文章推荐

    • 详解Python中的str.format方法• Python中format函数字符串格式化入门• python的format怎么用

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网