美文网首页
python 格式化字符串

python 格式化字符串

作者: AibWang | 来源:发表于2023-02-27 17:45 被阅读0次

    3种方式

    1. %占位符格式化字符串
    2. format格式化字符串
    3. fstring格式化字符串

    %占位符格式化字符串

    示例如下:

    "%02d %f %.4f %8.4f" % (1, 10.2, 8.8, 6.345)
    "my name is %s" % ("xiaoming")
    

    format格式化字符串

    示例如下:

    "{索引} ... {索引} ...".format(value1, value2, ...)
    "{0} + {1} = {2}".format(2, 3, 5)
    "{} is a {}.".format("xiaoming", "boy")
    

    索引可要可不要。

    format填充对齐

    {索引:[填充字符][对齐方式][宽度]}

    索引可不需要,默认填充字符为空格,<为左对齐,>为右对齐

    示例如下:

    # 按照宽度为20字符左对齐,不够的位置填充*
    "{0:*<20s}".format("nihao")
    # 按照宽度8,左对齐
    "{:<8.2f} {:0<6d}".format(1.2, 23)
    # 输出为"     1.2 000023"
    

    f-string格式化字符串

    f-string 格式化字符串并不需要占位,直接将输出变量填充到{}即可,变量也可直接为运算表达式

    示例如下:

    hi = "chaoliangwang"
    print(f'my name is {hi}')
    print(f'1 + 1 = {1+1}')
    

    相关文章

      网友评论

          本文标题:python 格式化字符串

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