Python Tricks: A Shocking Truth About String Formatting(一)

简介: Python Tricks: A Shocking Truth About String Formatting(一)

Python Tricks: A Shocking Truth About String Formatting
Remember the Zen of Python and how there should be “one obvious way to do something ?” You might scratch your head when you find out that there are four major ways to do string formatting in Python.

Today I’ll demonstrate how these four string formatting approaches work and what their respective strengths and weaknesses are. I’ll also give you my simple “rule of thumb”(经验法则) for how I pick the best general-purpose string formatting approach.

Let’s jump right in, as we’ve got a lot to cover. In order to have a simple toy example for experimentation, let’s assume we’ve got the following variables(or constants, really) to work with:

>>> errno = 50159747054
>>> name = 'Bob'

And based on these variables we’d like to generate an output string with the following error message:

'Hey Bob, there is  a 0xbadc0ffee error!'

Now, that error could really spoil a dev’s Monday morning! But we’re here to discuss string formatting today. So let’s get to work.

#1 - “Old Style” String Formatting
Strings in Python have a unique built-in operation that can be accessed with the %-operator. It’s a shortcut that lets you do simple positional formatting very easily. If you’ve ever worked with a printf-style function in C, you’ll instantly recognize how this works. Here’s a simple example:

>>> 'Hello, %s' % name
'Hello, Bob'

I’m using the %s format specifier here to tell Python where to subsitute the value of name, represented as a string. This is called “old style” string formatting.

In old style string formatting there are also other format specifiers available that let you control the output string. For example, it’s possible to convert numbers to hexadecimal notation or to add whitespace padding to generate nicely formatted tables and reports.

Here, I’m using the %x format specifier to convert an int value to a string and to represent it as a hexadecimal number:

>>> '%x' % errno
'badc0ffee'

The “old style” string formatting syntax changes slightly if you want to make multiple substitutions in a single string. Because the %-operator only takes one argument, you need to wrap the right-hand side in a tuple, like so:

>>> 'Hey %s, there is a 0x%x error!' %(name, errno)
'Hey Bob, there is a 0xbadc0ffee error!'

It’s also possible to refer to variable subsitutions by name in your format string, if you pass a mapping to the %-operator:

>>> 'Hey %(name)s, there is a 0x%(errno)x error!' % {
   "name":name, "errno":errno}'Hey Bob, there is a 0xbadc0ffee error!'

This makes your format strings easier to maintain and easier to modify in the future. You don’t have to worry about making sure the order you’re passing in the values matches up with the order the values are referenced in the format string.

I’m sure you’ve been wondering why this printf-style formatting is called “old style” string formatting. Well, let me tell you. It was technically superseded by “new style” formatting, which we’re going to talk about in a minute. But while “old style” formatting has been deemphasized, it hasn’t been deprecated. It is still supported in the latest version of Python.

#2 - “New Style” String Formatting
Python3 introduced a new way to do string formatting that was also later back-ported to Python2.7. This “new style” string formatting gets rid of the %-operator specifier syntax and makes the syntax for string formatting more regular. Formatting is now handled by calling a format() function on a string object.

You can use the format() function to do simple positional formatting, just like you could with “old style” formatting:

>>> 'Hello, {}'.format(name)
'Hello, Bob'

Or , you can refer to your variable substitutions by name and use them in any order you want. This is quite a powerful feature as it allows for re-arranging the order of display without changing the arguments passed to the format function:

>>> 'Hey {name}, there is a 0x{errno:x} error!'.format(name=name, errno=errno)
'Hey Bob, there is a 0xbadc0ffee error!'

This also shows that the syntax to format an int variable as a hexadecimal string has changed. Now we need to pass a format spec by adding a “:x” suffix after the variable name.

Overall, the format string syntax has become more powerful without complicating the simpler use cases. It pays off to read up on this string formatting mini-language in the Python documentation.

In Python3, this “new style” string formatting is preferred over %-style formatting. However, starting with Python3.6 there’s an even better way to format your strings. I’ll tell you all about it in the next section.

接下文 Python Tricks: A Shocking Truth About String Formatting(二)https://developer.aliyun.com/article/1618444

相关文章
|
1月前
|
存储 Java 索引
Python String详解!
本文详细介绍了Python中的字符串数据类型,包括其创建、访问、切片、反转及格式化等操作。文章涵盖字符串的基本概念、各种操作方法以及常用内置函数。通过多个示例代码展示了如何使用单引号、双引号和三重引号创建字符串,如何通过索引和切片访问与修改字符串内容,以及如何利用格式化方法处理字符串。此外,还介绍了字符串的不可变性及其在实际应用中的重要性。通过本文的学习,读者可以全面掌握Python字符串的使用技巧。
39 4
|
1月前
|
Go C++ Python
Python Tricks: String Conversion(Every Class Needs a ___repr__)
Python Tricks: String Conversion(Every Class Needs a ___repr__)
|
1月前
|
前端开发 Python
Python Tricks-- Abstract Base Classes Keep Inheritance in Check
Python Tricks-- Abstract Base Classes Keep Inheritance in Check
|
1月前
|
C++ Python
Python Tricks--- Object Comparisons:“is” vs “==”
Python Tricks--- Object Comparisons:“is” vs “==”
|
1月前
|
Python
Python Tricks: Nothing to Return Here
Python Tricks: Nothing to Return Here
|
1月前
|
C# Python
Python Tricks : Function Argument Unpacking
Python Tricks : Function Argument Unpacking
|
1月前
|
Python
Python Tricks : How to Write Debuggable Decorators
Python Tricks : How to Write Debuggable Decorators
|
1月前
|
Linux Go Python
Python Tricks :The Power Of Decorators
Python Tricks :The Power Of Decorators
|
1月前
|
API Python
Python Tricks : Fun With args and kwargs
Python Tricks : Fun With args and kwargs
|
1月前
|
Go C# Python
Python Tricks :Lambdas Are Single-Expression Functions 原创
Python Tricks :Lambdas Are Single-Expression Functions 原创