zoukankan      html  css  js  c++  java
  • 20200923-Python学习笔记4

    用%实现格式化

    常见的占位符

    %s :   字符串
    %d :    整数
    %f :    浮点数
    %x :    十六进制整数
    

    %运算符就是用来格式化字符串的。在字符串内部,%s示用字符串替换,%d表示用整数替换,有几个%?占位符,后面就跟几个变量或者值,顺序要对应好。如果只有一个%?,括号可以省略。

    >>> 'Hello,%s' % 'word'
    'Hello,word'
    >>> 'Hello,%s,you have $%d.' % ('kk',999999)
    'Hello,kk,you have $999999.'
    >>>
    

    %d 整数 和 %f 浮点数  举例:

    >>> print('%2d-%02d' % (3,1))
     3-01
    >>> print('%d-%02d' % (3,1))
    3-01
    >>> print('%d-%0d' % (3,1))
    3-1
    >>> print('%.f' % 3.1415926)
    3
    >>> print('%.3f' % 3.1415926)
    3.142
    >>> print('%.2f' % 3.1415926)
    3.14
    >>>
    >>> print('%d-%13d' % (3,1))
    3- 1
    >>> print('%d-%03d' % (3,1))
    3-001
    >>> print('%d-%9d' % (3,1))
    3- 1
    >>> print('%d-%09d' % (3,1))
    3-000000001
    >>>

    转义,用%% 表示 %

    >>> '%d %%' % 9
    '9 %'
    >>>
    

    format():格式化字符串函数,用{} : 代替 %          用传入的字符串依次代替{0}{1}{2},或者直接指定内容

    >>> "{}{}".format("hello","word")
    'helloword'
    >>> "{0} {1}".format("hello","word")
    'hello word'
    >>> "{0} {1}".format("word","hello")
    'word hello'
    >>> "{1} {0} {1}".format("hello","word")
    'word hello word'
    >>>

    >>> 'hello,{0},成绩下降了 {1:.1f}%'.format('小李',9.378)
    'hello,小李,成绩下降了 9.4%'
    >>>
    >>> print("网站名:{name},地址{url}".format(name="菜鸟",url="www.cainiao.com"))
    网站名:菜鸟,地址www.cainiao.com
    >>>

    f-string   函数  

    >>> name = " 269 "
    >>> f"hello,my name is {name}"
    'hello,my name is  269 '
    >>> number = 3
    >>> f"i have {number} books"
    'i have 3 books'
    >>> r = 4.6
    >>> s = 3.16 * r **2
    >>> print(f'the area of a circle with radius {r} is {s:.2f}')
    the area of a circle with radius 4.6 is 66.87
    >>>

    {r}被变量r的值替换,{s:.2f}被变量s的值替换,并且:后面的.2f指定了格式化参数,保留两位小数

  • 相关阅读:
    L2 L3 L4
    C 语言assert使用
    VIM 命令收藏
    C++继承实例
    关于 WinScp 的一点使用经验
    Boa服务器移植
    Android 去掉标题全屏显示
    sys下gpio操作
    linux下 XGCOM串口助手的安装
    linux中inittab文件详解
  • 原文地址:https://www.cnblogs.com/lookmefly/p/13719096.html
Copyright © 2011-2022 走看看