zoukankan      html  css  js  c++  java
  • 字符串的格式化

    1、%s  表示占位符

    如name = "诸葛孔%s" %"”明" 就等于name = "诸葛孔明"

    2、%d  与%s用法一样,只不过%s用于字符串,%d用于数字

    如name = " 鲁班%d号" %1

    即:name = "鲁班1号"

    3、%%  第一个%表示转义

    4、join的使用

    5、format函数用法

    format用法

     相对基本格式化输出采用‘%’的方法,format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’

    使用方法由两种:b.format(a)和format(a,b)。

    1、基本用法

      (1)不带编号,即“{}”

      (2)带数字编号,可调换顺序,即“{1}”、“{2}”

      (3)带关键字,即“{a}”、“{tom}”

    >>> print('{} {}'.format('hello','world')) # 不带字段
    hello world
    >>> print('{0} {1}'.format('hello','world')) # 带数字编号
    hello world
    >>> print('{0} {1} {0}'.format('hello','world')) # 打乱顺序
    hello world hello
    >>> print('{1} {1} {0}'.format('hello','world'))
    world world hello
    >>> print('{a} {tom} {a}'.format(tom='hello',a='world')) # 带关键字
    world hello world

    2、进阶用法

    (1)< (默认)左对齐、> 右对齐、^ 中间对齐、= (只用于数字)在小数点后进行补齐

    (2)取位数“{:4s}”、"{:.2f}"等

    >>> print('{} and {}'.format('hello','world')) # 默认左对齐
    hello and world
    >>> print('{:10s} and {:>10s}'.format('hello','world')) # 取10位左对齐,取10位右对齐
    hello and world
    >>> print('{:^10s} and {:^10s}'.format('hello','world')) # 取10位中间对齐
    hello and world
    >>> print('{} is {:.2f}'.format(1.123,1.123)) # 取2位小数
    1.123 is 1.12
    >>> print('{0} is {0:>10.2f}'.format(1.123)) # 取2位小数,右对齐,取10位
    1.123 is 1.12

     
  • 相关阅读:
    利用书签栏作插入时失败告终
    组以逗号分隔的子串及跨平update join
    ms_sql:drop and create a job
    why dicePlayer cannot player with defy mb526
    好像国庆三天是可以加班工资计了
    msssql 用numberic(38)替代int去解决int不够的问题
    C#的switch与二维数组.....
    某牛人所留的联系方式
    封装对象类
    数据库访问小列题
  • 原文地址:https://www.cnblogs.com/meng-xiaoyi/p/14105968.html
Copyright © 2011-2022 走看看