python中format函数如何使用

作者:silencement 时间:2022-06-18 06:50:41 

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

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

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 = ['脚本之家', 'www.jb51.net']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的

输出结果

网站名:脚本之家, 地址 www.jb51.net
网站名:脚本之家, 地址 www.jb51.net
网站名:脚本之家, 地址 www.jb51.net

来源:https://www.py.cn/faq/python/12584.html

标签:python,format函数
0
投稿

猜你喜欢

  • 让IE6更快的走向灭亡

    2010-02-03 15:05:00
  • 各种Python库安装包下载地址与安装过程详细介绍(Windows版)

    2021-01-27 14:00:05
  • css行高:line-height属性详解

    2008-06-24 11:42:00
  • Python requests的SSL证书验证方式

    2021-10-06 09:21:51
  • Python搜索引擎实现原理和方法

    2023-06-26 05:35:32
  • Python Json数据文件操作原理解析

    2022-10-27 19:00:32
  • Python使用urllib2模块实现断点续传下载的方法

    2021-12-27 05:20:01
  • 如何创建SQL Server 2000故障转移群集

    2009-02-13 17:18:00
  • Dreamweaver制作技巧四则

    2008-01-04 09:42:00
  • Python中断多重循环的几种方式详解

    2022-05-09 21:44:04
  • Python数据可视化实现正态分布(高斯分布)

    2022-10-28 03:31:29
  • Python OpenCV实现姿态识别的详细代码

    2023-05-27 23:42:31
  • Python try-except-else-finally的具体使用

    2022-10-18 14:31:45
  • Python+AutoIt实现界面工具开发过程详解

    2023-06-17 20:39:47
  • js实现登录注册框手机号和验证码校验(前端部分)

    2023-09-13 02:41:37
  • Python实现数据集划分(训练集和测试集)

    2022-11-29 23:54:11
  • python实现从pdf文件中提取文本,并自动翻译的方法

    2021-06-08 18:55:56
  • 你是真正的用户体验设计者吗? Ⅰ

    2008-03-20 13:42:00
  • Python通过TensorFlow卷积神经网络实现猫狗识别

    2023-09-29 10:59:56
  • Python实现为PDF去除水印的示例代码

    2023-03-05 04:27:56
  • asp之家 网络编程 m.aspxhome.com