美文网首页
str.format()

str.format()

作者: zelda2333 | 来源:发表于2020-01-04 15:28 被阅读0次

格式化字符串的函数 str.format(),基本语法是通过 {} 和 :

  1. format 函数可以接受不限个参数,位置可以不按顺序
    实例
> "{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
  'hello world'
> "{0} {1}".format("hello", "world")  # 设置指定位置
  'hello world' 
> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
  'world hello world'
  1. 也可以设置参数:
> print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))  
  网站名:菜鸟教程, 地址 www.runoob.com

# 通过字典设置参数
> site = {"name": "菜鸟教程", "url": "www.runoob.com"}
> print("网站名:{name}, 地址 {url}".format(**site))
  网站名:菜鸟教程, 地址 www.runoob.com

# 通过列表索引设置参数
> my_list = ['菜鸟教程', 'www.runoob.com']
> print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的
  网站名:菜鸟教程, 地址 www.runoob.com
  1. 也可以向 str.format() 传入对象
> class AssignValue(object):
      def __init__(self, value):
          self.value = value
> my_value = AssignValue(6)
> print('value 为: {0.value}'.format(my_value))  # "0" 是可选的

参考:菜鸟--Python format 格式化函数

相关文章

  • js实用函数集;

    Menu str.format() str.format()

  • Python 标准化输出

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

  • str.format()

    格式化字符串的函数 str.format(),基本语法是通过 {} 和 : format 函数可以接受不限个参数,...

  • str.format简介

    一、python的格式化输出从2.6以后format格式化方法代替了%格式化,%的格式化当然也可以使用,不过建议全...

  • 读《菜鸟教程--Python3教程》查漏补缺

    菜鸟教程 1. str.format() 的基本用法 <<< print('{}网址: "{}!"'.format...

  • pass a dict to str.format

  • str.format [cheat sheet]

    转载须注明出处:简书@Orca_J35 | GitHub@orca-j35,所有笔记均托管于 python_not...

  • Python 的数据模型

    %r、str.format 中的 !r、v(一个对象)都是调用该对象的 repr 方法print(object) ...

  • BMR计算器

    字符串分割str.split()字符串格式化输出,使用{}占位 str.format()如:‘{}公斤,{}厘米’...

  • str.format()的基础用法

    在很多样例中看到了.format(),虽然大致猜出来是一种参数传入以及格式化,还是查了查它的具体用法。接下来,开始...

网友评论

      本文标题:str.format()

      本文链接:https://www.haomeiwen.com/subject/dtnxactx.html