首页系统综合问题Python学习教程:Python3之字符串格式化format函数详解(上)

Python学习教程:Python3之字符串格式化format函数详解(上)

时间2023-02-17 17:25:43发布分享专员分类系统综合问题浏览155

今天小编给各位分享format函数的知识,文中也会对其通过Python学习教程:Python3之字符串格式化format函数详解(上)和format在python中的用法是什么?等多篇文章进行知识讲解,如果文章内容对您有帮助,别忘了关注本站,现在进入正文!

内容导航:

  • Python学习教程:Python3之字符串格式化format函数详解(上)
  • format在python中的用法是什么?
  • format在python中的用法
  • format在python中的用法
  • 一、Python学习教程:Python3之字符串格式化format函数详解(上)

    Python学习教程:Python3之字符串格式化format函数详解(上)

    概述

    在Python3中,字符串格式化操作通过format()方法或者f’string’实现。而相比于老版的字符串格式化方式,format()方法拥有更多的功能,操作起来更加方便,可读性也更强。该函数将字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号{}作为特殊字符代替%。

    位置设定

    默认位置

    不指定格式化位置,按照默认顺序格式化

    S = 'I {} {}, and I\'am learning'.format('like', 'Python')print(S)

    示例结果:

    I like Python, and I'am learning

    设置位置

    设置数字顺序指定格式化的位置

    S = 'I {0} {1}, and I\'am learning'.format('like', 'Python')print(S)# 打乱顺序S = 'I {1} {0} {1}, and I\'am learning'.format('like', 'Python')print(S)

    示例结果:

    I like Python, and I'am learningI Python like Python, and I'am learning

    设置关键字

    设置关键字指定格式化的内容

    S = 'I {l} {p}, and I\'am learning'.format(p='Python', l='like')print(S)S = 'I {p} {l}, and I\'am learning'.format(p='Python', l='like')print(S)

    示例结果:

    I like Python, and I'am learningI Python like, and I'am learning

    参数传递

    我们可以传入各种类型参数格式化字符串,即不限于字符串变量或数字等。

    元组传参

    利用元组传参,传参形式 *tuple

    # 定义一个元组T = 'like', 'Python'# 不指定顺序S = 'I {} {}, and I\'am learning'.format(*T)print(S)# 指定顺序S = 'I {0} {1}, and I\'am learning'.format(*T)print(S)

    示例结果:

    I like Python, and I'am learningI like Python, and I'am learning

    字典传参

    # 定义一个字典D = {'l':'like', 'p':'Python'}# 指定键确定顺序S = 'I {l} {p}, and I\'am learning'.format(**D)print(S)

    示例结果:

    I like Python, and I'am learning

    列表传参

    # 定义一个列表L0 = ['like', 'Python']L1 = [' ', 'Lerning']# `[]`前的0、1用于指定传入的列表顺序S = 'I {0[0]} {1[1]}, and I\'am learning'.format(L0, L1)print(S)

    示例结果:

    I like Lerning, and I'am learning

    下期的Python学习教程会继续为大家更新!

    一、format在python中的用法是什么?

    常见于字符串格式化。

    比如 print("第{0}天".format(d))。会打印"第5天"。

    python3的format函数中s表示格式化字符串类型数据。{:>15s}表示右对齐15个字符,左侧空白默认用空格填充。{:15s}:{:

    爱资源吧版权声明:以上文中内容来自网络,如有侵权请联系删除,谢谢。

    format函数
    聊聊ISO吧,到底有哪些ISO 记一次系统备份详细教程