zoukankan      html  css  js  c++  java
  • python-格式化

    格式化

    1.用%运算符格式化字符串

    常见的占位符:

    占位符 替换内容
    %s 字符串
    %d 整数
    %f 浮点数
    %x 十六进制数

    在字符串内部,有几个%?,后边就要对应几个变量或者值,顺序不能乱

    %s会把任何数据类型转换为字符串

    例如:

     1 >>> print('My name is %s' , % 'Monica')
     2 My name is Monica
     3 
     4 >>> print("I'm %d years old" , % 20)
     5 I'm 20 years old
     6 
     7 >>> ' Hi,%s ,you have $%.2f ' % ('Monica',123.4567)
     8 'Hi,Monica,you have $123.45'
     9 
    10 >>> ' %s has %s dogs ' % ('Monica',2)
    11 'Monica has 2 dogs'

    若字符串内部已经有%,需要转义,用%%表示%

    2. format()方法

    用传入的参数依次替换字符串内的占位符{0}{1}……

    例如:

    1 >>> 'Hi,{0},my name is {1}'.format('Monica','Ross')
    2 Hi,Monica,my name is Ross

    3. f-string 以f开头的字符串

    它和普通字符串不同之处在于,字符串如果包含{xxx},就会以对应的变量替换

    例如:

    1 >>> a=3.123
    2 >>> b=2*3
    3 >>> print(f'The area is {a:.2f} and the length is {b}')
    4 The area is 3.12 and the length is 6
  • 相关阅读:
    书_Delphi
    20160226
    SVG_style_script
    辅助
    电影_Z
    Windows下软件调试
    20160221
    Qt5.3.2_vs10_发布时所需DLL的路径
    android intent 传数据
    android 消息机制
  • 原文地址:https://www.cnblogs.com/canneddream/p/14070717.html
Copyright © 2011-2022 走看看