zoukankan      html  css  js  c++  java
  • python fstrings !表达式

    近期看一些框架的文档时发现, python的f-stringsf"{xxx!r}"的写法, 就官网看了一波文档, 特此记录一下, 顺便完善一下f-strings的使用

    f-strings的由来

    目前, python有三种字符串格式化方法: %/format/f-strings, 简单使用见: Python格式化输出

    f-strings主要是有人认为 %format使用起来太麻烦了而提出的. 由于f-strings晚于 %format, 所以f-strings既有%方法的简便, 又有format方法的强大.

    详见: PEP 498 -- Literal String Interpolation

    总的来说, f-string在功能方面不逊于其余两种方法,同时性能又优于二者,且使用起来也更加简洁明了
    但需要注意的是, python的版本不低于3.6

    f-strings的使用

    语法

    格式如下:

    f"<text>{<key> <optional !s,!r,!a> <optional :[填充][对齐][宽度][数字分隔][精度][类型]>}<text> ... "
    
    >>> name = "lczmx"
    >>> age = 20
    >>> score = 59.99
    >>> f"student name {name}, age {age}, score {score}"
    'student name lczmx, age 20, score 59.99'
    >>> f"student name {name}, age {age}, score {score:.1f}"
    'student name lczmx, age 20, score 60.0'
    

    {}里面的格式和format方法一致, 这里: format 方法

    例子

    一般使用

    >>> name = "lczmx"
    >>> f"username: {name}"
    'username: lczmx'
    

    !s/!r/!a使用

    !s在表达式上调用str(), !r调用表达式上的repr(), !a调用表达式上的ascii()
    关于ascii, 见: ascii()

    >>> class A:
    ...     def __str__(self):
    ...         return "str A对象"
    ...     def __repr__(self):
    ...         return "repr A对象"
    ... 
    >>> a_obj = A()
    >>> f"str: {a_obj!s} repr: {a_obj!r} ascii: {a_obj!a}"
    'str: str A对象 repr: repr A对象 ascii: repr A\\u5bf9\\u8c61'
    
    

    {=}表达式

    >>> name = "lczmx"
    >>> f"{name=}"
    "name='lczmx'"
    >>> f"{name=!s}"
    'name=lczmx'
    >>> f"{name  =: >7}"
    'name  =  lczmx'
    

    其他例子

    # {index/key:[填充][对齐][宽度][数字分隔][精度][类型]}
    
    name = "lczmx"
    
    # ############## 填充 + 对齐 + 宽度
    
    # lczmx---------------
    print(f"{name:-<20}")
    # -------lczmx--------
    print(f"{name:-^20}")
    # ---------------lczmx
    print(f"{name:->20}")
    
    # ############## 数字分隔符
    
    number = 123456789
    # 123,456,789
    print(f"{number:,}")
    # 123_456_789
    print(f"{number:_}")
    
    # ############## 精度
    
    pi = 3.1415926
    # pi = 3.14
    print(f"{pi = :.2f}")
    # pi = 3
    print(f"{pi = :.0f}")
    
    # ############## 类型转换
    num = 15
    # 1111
    print(f"{num:b}")
    # 17
    print(f"{num:o}")
    # 15
    print(f"{num:d}")
    # f
    print(f"{num:x}")
    # 0xf
    print(f"{num:#x}")
    # 0XF
    print(f"{num:#X}")
    
    value = 0.452
    # 45.2%
    print(f"{value:.1%}")
    # 1.23e+08
    print(f"{number:.2e}")
    

    更多语法, 见: 格式规格迷你语言

    datetime结合

    .strftime()的格式一样, 这里用一个表格列出了

    格式描述符 含义 显示样例
    %a 星期几 (缩写) "Sun"
    %A 星期几 (全名) "Sunday"
    %w 星期几 (数字,0 是周日,6 是周六) "0"
    %u 星期几 (数字,1 是周一,7 是周日) "7"
    %d 日 (数字,以 0 补足两位) "07"
    %b 月 (缩写) "Aug"
    %B 月 (全名) "August"
    %m 月 (数字,以 0 补足两位) "08"
    %y 年 (后两位数字,以 0 补足两位) "14"
    %Y 年 (完整数字,不补零) "2014"
    %H 小时 (24小时制,以 0 补足两位) "23"
    %I 小时 (12小时制,以 0 补足两位) "11"
    %p 上午/下午 "PM"
    %M 分钟 (以 0 补足两位) "23"
    %S 秒钟 (以 0 补足两位) "56"
    %f 微秒 (以 0 补足六位) "553777"
    %z UTC偏移量 (格式是 ±HHMM[SS],未指定时区则返回空字符串) '"1030"
    %Z 时区名 (未指定时区则返回空字符串) "EST"
    %j 一年中的第几天 (以 0 补足三位) "195"
    %U 一年中的第几周 (以全年首个周日后的星期为第0周,以 0 补足两位) "27"
    %w 一年中的第几周 (以全年首个周一后的星期为第0周,以 0 补足两位) "28"
    %V 一年中的第几周 (以全年首个包含1月4日的星期为第1周,以 0 补足两位) "28"
    import datetime
    
    t = datetime.datetime.now()
    
    # the time is 2021-12-11 12:05:02
    print(f'the time is {t:%Y-%m-%d %X}')
    
    

    调用方法

    f-strings可以在{}中像正常的python代码一样使用

    data = {
        "username": "lczmx",
        "password": "123456"
    }
    
    # username = lczmx, password = 123456
    print(f"username = {data['username']}, password = {data.get('password')}")
    

    本文来自博客园,作者:403·Forbidden,转载请注明原文链接:https://www.cnblogs.com/lczmx/p/15684590.html

  • 相关阅读:
    「UVA12293」 Box Game
    「CF803C」 Maximal GCD
    「CF525D」Arthur and Walls
    「CF442C」 Artem and Array
    LeetCode lcci 16.03 交点
    LeetCode 1305 两棵二叉搜索树中的所有元素
    LeetCode 1040 移动石子直到连续 II
    LeetCode 664 奇怪的打印机
    iOS UIPageViewController系统方法崩溃修复
    LeetCode 334 递增的三元子序列
  • 原文地址:https://www.cnblogs.com/lczmx/p/15684590.html
Copyright © 2011-2022 走看看