Home  >  Article  >  Backend Development  >  Summary of methods for implementing string formatting in Python

Summary of methods for implementing string formatting in Python

高洛峰
高洛峰Original
2017-02-21 17:01:261364browse

Python2.6+ adds the str.format function to replace the original '%' operator. Its use is more intuitive and flexible than '%'. Here's a detailed introduction to how to use it.

The following is an example of using '%':

""
"PI is %f..." % 3.14159 # => 'PI is 3.141590...'
"%d + %d = %d" % (5, 6, 5+6) # => '5 + 6 = 11'
"The usage of %(language)s" % {"language": "python"} # => 'The usage of python'

The format is very similar to printf in C language, right? Since '%' is an operator, only one parameter can be placed on the left and right sides. Therefore, multiple values ​​on the right need to be included in tuples or dictionaries. Tuples and dictionaries cannot be used together, which lacks flexibility.

The same example is rewritten using the format method:

"PI is {0}...".format(3.14159) # => 'PI is 3.14159...'
"{0} + {1} = {2}".format(5, 6, 5+6) # => '5 + 6 = 11'
"The usage of {language}".format(language = "Python") # => 'The usage of Python'

Isn’t it very intuitive? (Of course, I also like the former format expression method when using C language:-) )

Format string

"{named} consist of intermingled character {0} and {1}".format("data", "markup", \
  named = "Formats trings")
format(10.0, "7.3g") # => '   10'
"My name is {0} :-{{}}".format('Fred') # => 'My name is Fred :-{}'

Pay attention to the '\' in the first line. If a statement needs to be newline, it must be escaped with a backslash at the end.

Using '%', you cannot mix tuples and dictionaries like this. In fact, here are named parameters, a feature of Python. You can use *args, **kwargs syntax to expand collections and dictionaries when defining arrays. It should be noted that the named parameters are placed at the end.

The second statement indicates that the format built-in function is used to format a single value.

The third statement represents the escape of {}, because {} is a special character in the formatted string and cannot be displayed directly. The escaping method is to nest one level more.

Using properties and indexes

"My name is {0.name}".format(open('out.txt', 'w')) # => 'My name is out.txt'

'{0.name}' is equivalent to calling the object It is also possible to use indexes for the attribute open('out.txt', 'w').name

"My name is {0[name]}".format(dict(name='Fred')) # => 'My name is Fred'

.

obj[key] is equivalent to obj.____getitem____('key')

Standard specifiers (Specifiers)

Written in C Language programmers should be aware of the complexity of printf. format also defines a number of standard specifiers that are used to interpret the format of a value and then insert it into the string. For example:

"My name is {0:8}".format('Fred') # => 'My name is Fred  '

':' is followed by the specifier. In the above example, the specifier has only one '8' (minimumwidth), which means The inserted value width must be at least 8. 'Fred' only has 4, so 4 more spaces are added. The detailed format of the

specifier is:

[[fill]align][sign][#][0][minimumwidth][.precision][type] (Not more concise than C's printf!)

Note: '[]' means that the element is optional. Therefore, all format specifiers are optional! Like the previous examples, this is almost never used (just to make the example clearer). In fact, these are very useful.

Let’s look at them one by one:
1. [fill]align means arrangement. When the minimumwidth is set larger than the inserted value, there is a blank space, just like 'My name is Fred' in the previous example. By default, the space is placed on the right, which means that the inserted value is left aligned by default. If we try {0:>8}, we will find that the result becomes 'My name is Fred'.
fill represents the characters used to fill the blank space. Fill is only useful if align is specified! align can be the following identifier:

  • 229efb477b7f728e14cf29ed8b7c4ddf right aligned

  • = Place blank space after the align mark, which is only valid for numbers. What does that mean? As will be discussed below, align displays the positive and negative signs of numbers, which is also only valid for numbers. If '=' is specified, the positive and negative signs of the number will be displayed in front of the blank space. For example: format(-12, "0=8") # => '-0000012' Note that the built-in function format for formatting a single value is used here. '0' is the fill element, which is used to fill the blank space; '=' is the mark; '8' means that the minimum width is 8, so there are only 5 blank spaces. What about align? align actually describes the display method of plus and minus signs. The default '-' is used here, which will be discussed later.

  • ^ Center alignment

2. sign digital symbol, only valid for numbers.

  • + Show plus and minus signs

  • - Do not show plus sign, show minus sign. Without specifying a minimum width, negative numbers always occupy one more symbol position than positive numbers. Default

  • ' ' (a space) Use a blank space to replace the plus sign

3, # The prefix of the displayed number indicates the decimal system ( 0b, 0o, 0x)

4, 0 Fill the blank space with '0'.

5. minimumwidth specifies the minimum width, which has been used many times.

6. .precision 'precision' is a decimal number, indicating how many decimal places to display.

7. type Value type:

①Integer type:

  • b Binary

  • c Character type, convert numbers into characters representing unicode

  • d Decimal

  • o Octal

  • x Hexadecimal, display lower case letters

  • X Hexadecimal, display upper case letters

  • n Behavior with d The same, using the local number representation

  • '' (empty, no spaces) Same as d

②Floating point number

  • e 科学计数法表示,小写e

  • E 科学计数法表示,大写E

  • f 显示为定点数,默认小数点后六位

  • F 同f

  • g 自动选择是否用科学记数法表示

  • G 同g

  • n 同g,使用本地表示方式

  • % 使用百分比表示

  • ''(空) 同g

每个对象可以重写自己的格式化说明符,例如datatime类重写了后可以这样表示:

"Today is: {0:%a %b %d %H:%M:%S %Y}".format(datetime.now())

预先转换

':'之后是格式说明符,之前还可以加预先转换的标识

  • !r 调用对象的_repr_方法来转换成标准字符串

  • !s 调用对象的_str_方法来转换成字符串

重写_format_方法

我们在格式化一个字符串时,首先格式化每个值,然后再插入字符串内。格式化值调用的就是format内置方法。format则是简单地调用该值的_format_方法。

def format(value, format_spec):
  return value.__format__(format_spec)

在object类内实现了_format方法,只是将本身用str()转换成字符串,然后将字符串传入内置的format方法,实际上就是调用转换为字符串后的format_方法。

class object:
  def __format__(self, format_spec):
    return format(str(self), format_spec)

int/float/str自身实现了_format_方法,前面已经介绍了它们各自的说明符。

结束语

还有一点儿是自定义Formatter,不过平常也用不到。留作下篇string模块源码解读的内容吧。建议有兴趣的朋友多看看Python标准库的源码,很有学习价值。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。

更多Python实现字符串格式化的方法小结相关文章请关注PHP中文网!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn