• Python


    0. 摘要

      Python支持多种格式化字符串的方法,包括%-fromatting、str.format()、f-strings三种,f-strings是Python3.6以后出现的一种新方法,相比其他方法,更简洁、易读、速度快。

    1. %-formatting

    %格式化字符串是Python中比较老的一种用法。

    例1:只有一个变量格式化输出

    >>> name = 'Jack'
    >>> 'Hello, %s.' % name
    'Hello, Jack.'

    例2:有多个变量需要替换时,使用这些变量的元祖。

    >>> name = 'Jack'
    >>> age = 20
    >>> "Hello, I'm %s, %d years old." % (name, age)
    "Hello, I'm Jack, 20 years old."

     

    2. str.format()

      在Python2.6中引入了更新的格式化方式str.format()

    例1:需替换的字段用{}标记

    >>> name = 'Jack'
    >>> age = 20
    >>> "Hello, I'm {}, {} years old.".format(name, age)
    "Hello, I'm Jack, 20 years old."

    例2:使用索引引用变量,这样变量和替换的标记就不必一一对应。

    >>> name = 'Jack'
    >>> age = 20
    >>> language = 'Python'
    >>> "Hello, I'm {0}, {1} years old. My name is {0}".format(name, age)
    "Hello, I'm Jack, 20 years old. My name is Jack"

    例3:使用名称引用变量替换

    >>> name = 'Jack'
    >>> age = 20
    >>> "Hello, I'm {na}, {ag} years old. My name is {na}".format(na=name, ag=age)
    "Hello, I'm Jack, 20 years old. My name is Jack"

    3. f-strings

      Python3.6中使用了一种更加简洁明了的格式化方法,该方法允许在字符串中嵌入变量、表达式。该方法使用格式: f"string" 

    例1:

    >>> name = 'Jack'
    >>> age = 20
    >>> f"Hello, I'm {name}, {age} years old."
    "Hello, I'm Jack, 20 years old."

    例2:使用任意表达式

    >>> f"{20*5}"
    '100'

    例3:调用函数

    >>> name = "Jack"
    >>> f"Hello, I'm {name.lower()}"
    "Hello, I'm jack"

    例4:多行文本

    >>> f"""
    ... I'm {name},
    ... I'm {age} years old.
    ... """
    "
    I'm Jack,
    I'm 20 years old.
    "

    参考文档:

    [博客] python3 f-string格式化字符串的高级用法(中文)

    [官方文档] PEP 498 -- Literal String Interpolation (英文)

    [博客] Python String Formatting Best Practices(英文)

    Andraw|朱标
  • 相关阅读:
    下拉框插件开发 (一)
    工厂模式 抽象工厂模式
    闭包 构建函数 简单工厂模式
    js继承
    浅谈js观察者模式
    浅谈js单例模式
    localstorage本地存储
    Vi 配置文件
    Vi Command
    我的Firs博客
  • 原文地址:https://www.cnblogs.com/zhubiao/p/9486996.html
Copyright © 2020-2023  润新知