- Learn Programming in Python with Cody Jackson
- Cody Jackson
- 414字
- 2021-06-10 19:06:09
String formatting
Formatting strings is simply a way of presenting the information on the screen in a way that conveys the information best. Some examples of formatting are creating column headers, dynamically creating a sentence from a list or stored variable, or stripping extraneous information from the strings, such as excess spaces.
Python supports the creation of dynamic strings. This means you can create a variable containing a value of some type (such as a string or number) and then call that value into your string. You can process a string the same way as in C if you choose to, such as %d for integers and %f for floating-point numbers.
The following screenshot shows this legacy method of formatting strings. Lines 1 and 2 define the substitution values that will be used. Line 3 creates the string that will be output. Note that the substitution values are identified by position, as well as the fact that, when using an interactive Python session, the interpreter will patiently wait until all required information is presented. In this case, an extra parenthesis is added to complete the print() function:
Since Python 2.6, an alternate way of formatting strings is to use a method call, shown in the following screenshot. Line 21 shows positional substitution, line 22 shows keyword substitution, and line 23 shows relative position substitution. Relative position may be the most common, but it can get out of hand with more than just a few substitutions.
The following screenshot shows an example of method string formatting:
Method string formatting is similar to the C# method, but it hasn't replaced the expression formatting. While the expression formatting is deprecated, it is still available in Python 3. However, method formatting provides more capabilities, so expression formatting is primarily found in legacy code.
It's worth pointing out that, while you can frequently get the output you desire by calling the string object directly (as demonstrated in the previous example), it doesn't always work the way you want. Sometimes the object will only return a memory address, particularly if you are trying to print an instance of a class (which will be discussed in Chapter 4, Functions and Object Oriented Programming, in the Classes and instances section). Generally speaking, it's better to explicitly call the print() function if you want a statement evaluated and printed out. Otherwise, you don't know exactly what value it will return.
- JBoss Weld CDI for Java Platform
- 人臉識別原理及算法:動態人臉識別系統研究
- PostgreSQL 11從入門到精通(視頻教學版)
- 青少年Python編程入門
- 軟件測試教程
- 詳解MATLAB圖形繪制技術
- 新印象:解構UI界面設計
- Xcode 6 Essentials
- Python數據可視化之美:專業圖表繪制指南(全彩)
- Advanced Python Programming
- Node.js 6.x Blueprints
- JavaEE架構與程序設計
- Getting Started with the Lazarus IDE
- 小學生C++趣味編程從入門到精通
- Mastering Magento Theme Design