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

    字符串格式化操作符(%)只适用于字符串类型,非常类似于C 语言里面的printf()函数的字符串格式化,甚至所用的符号都一样,都用百分号(%),并且支持所有printf()式的格式化操作。语法如下:
    format_string % string_to_convert
    format_string为格式标记字符串,形式为“%cdoe”;string_to_convert 为要格式化的字符串,如果是两个以上,则需要用小括号括起来。

    字符串格式化符号
    格式化符号说明
    %c 转换成字符(ASCII 码值,或者长度为一的字符串)
    %r 优先用repr()函数进行字符串转换(Python2.0新增)
    %s 优先用str()函数进行字符串转换
    %d / %i  转成有符号十进制数
    %u 转成无符号十进制数
    %o 转成无符号八进制数
    %x / %X (Unsigned)转成无符号十六进制数(x / X 代表转换后的十六进制字符的大
    小写)
    %e / %E 转成科学计数法(e / E控制输出e / E)
    %f / %F 转成浮点数(小数部分自然截断)
    %g / %G %e和%f / %E和%F 的简写
    %% 输出%
    >>> #打印字符串
    >>> print('My name is %s' % 'Rusky')
    My name is Rusky
    >>> #打印整数
    >>> print('He is %d years old' % (26))
    He is 26 years old
    >>> #打印浮点数
    >>> print('His height is %f M' % (1.78))
    His height is 1.780000 M
    >>> print('His height is %.2f M' % (1.78))
    His height is 1.78 M
    >>> #指定占位符宽度
    >>> print('Name:%10s Age:%8d Height:%8.2f' % ('Rusky',26,1.78))
    Name:     Rusky Age:      26 Height:    1.78
    >>> #指定占位符宽度-左对齐
    >>> print('Name:%-10s Age:%-8d Height:%-8.2f' % ('Rusky',26,1.78))
    Name:Rusky      Age:26       Height:1.78    
    >>> #科学计数法
    >>> format(3.141592611111111111111,'.2e')
    '3.14e+00'
    >>> 
    

      

  • 相关阅读:
    mysql修改数据表名
    HDU 5742 It's All In The Mind (贪心)
    HDU 5752 Sqrt Bo (数论)
    HDU 5753 Permutation Bo (推导 or 打表找规律)
    HDU 5762 Teacher Bo (暴力)
    HDU 5754 Life Winner Bo (博弈)
    CodeForces 455C Civilization (并查集+树的直径)
    CodeForces 455B A Lot of Games (博弈论)
    CodeForces 455A Boredom (DP)
    HDU 4861 Couple doubi (数论 or 打表找规律)
  • 原文地址:https://www.cnblogs.com/rusking/p/5044273.html
Copyright © 2011-2022 走看看