最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Python中,带填充和设置对齐方式的,格式化字符串输出

Python crifan 10915浏览 0评论

【问题】

想要获得这样的效果:

——-abc
——abcd
—–abcde

【解决过程】

1.折腾半天,终于从Python的手册中,找到对应的用法了。

完整代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function:
【已解决】Python中,带填充和设置对齐方式的,格式化字符串输出
https://www.crifan.com/python_string_format_fill_with_chars_and_set_alignment

Author:     Crifan Li
Version:    2012-12-26
Contact:    admin at crifan dot com
"""


def printFillWith():
    inputStrList = [
        "abc",
        "abcd",
        "abcde",
    ];
    
    #refer:
    #Python 2.7.3 Manual -> 
    #7.1.3.1. Format Specification Mini-Language
    #7.1.3.2. Format examples
    
    for eachStr in inputStrList:
        #print '{:->10}'.format(eachStr);
        print '{0:->10}'.format(eachStr);
        # -------abc
        # ------abcd
        # -----abcde

    for eachStr in inputStrList:
        print '{0:-<20}'.format(eachStr);
        # abc-----------------
        # abcd----------------
        # abcde---------------
    
    for eachStr in inputStrList:
        print '{0:*^30}'.format(eachStr);
        # *************abc**************
        # *************abcd*************
        # ************abcde*************

if __name__ == "__main__":
    printFillWith();

 

【总结】

总的来说就是类似于:

‘{0:-<20}’.format(eachStr);

的写法,即可。

 

更多参数的含义,摘录手册中的部分解释,如下:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]

fill        ::=  <a character other than ‘}’>

align       ::=  "<" | ">" | "=" | "^"

sign        ::=  "+" | "-" | " "

width       ::=  integer

precision   ::=  integer

type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

 

align:

OptionMeaning
'<'Forces the field to be left-aligned within the available space (this is the default for most objects).
'>'Forces the field to be right-aligned within the available space (this is the default for numbers).
'='Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types.
'^'Forces the field to be centered within the available space.

 

sign:

OptionMeaning
'+'indicates that a sign should be used for both positive as well as negative numbers.
'-'indicates that a sign should be used only for negative numbers (this is the default behavior).
spaceindicates that a leading space should be used on positive numbers, and a minus sign on negative numbers.

 

对于字符string:

TypeMeaning
's'String format. This is the default type for strings and may be omitted.
NoneThe same as 's'.

对于数字integer :

TypeMeaning
'b'Binary format. Outputs the number in base 2.
'c'Character. Converts the integer to the corresponding unicode character before printing.
'd'Decimal Integer. Outputs the number in base 10.
'o'Octal format. Outputs the number in base 8.
'x'Hex format. Outputs the number in base 16, using lower- case letters for the digits above 9.
'X'Hex format. Outputs the number in base 16, using upper- case letters for the digits above 9.
'n'Number. This is the same as 'd', except that it uses the current locale setting to insert the appropriate number separator characters.
NoneThe same as 'd'.

 

浮点和整数(floating point and decimal ):

TypeMeaning
'e'Exponent notation. Prints the number in scientific notation using the letter ‘e’ to indicate the exponent.
'E'Exponent notation. Same as 'e' except it uses an upper case ‘E’ as the separator character.
'f'Fixed point. Displays the number as a fixed-point number.
'F'Fixed point. Same as 'f'.
'g'

General format. For a given precision p >= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude.

The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp. Then if -4 <= exp < p, the number is formatted with presentation type 'f' and precision p-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it.

Positive and negative infinity, positive and negative zero, and nans, are formatted as inf, -inf, 0, -0 and nan respectively, regardless of the precision.

A precision of 0 is treated as equivalent to a precision of 1.

'G'General format. Same as 'g' except switches to 'E' if the number gets too large. The representations of infinity and NaN are uppercased, too.
'n'Number. This is the same as 'g', except that it uses the current locale setting to insert the appropriate number separator characters.
'%'Percentage. Multiplies the number by 100 and displays in fixed ('f') format, followed by a percent sign.
NoneThe same as 'g'.

转载请注明:在路上 » 【已解决】Python中,带填充和设置对齐方式的,格式化字符串输出

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
90 queries in 0.210 seconds, using 22.13MB memory