python中格式化字符串
Strings are one of the most essential and used datatypes in programming. It allows the computer to interact and communicate with the world, such as printing instructions or reading input from the user. The ability to manipulate and formate strings give the programmer the power to process and handle text, for example, extract user input from websites forms, data from processed text, and use this data to perform activities such as sentimental analysis. Sentimental analysis is a subfield of natural language processing that allows the computer to classify emotions — negative, positive, or neutral — based on a piece of text.
小號 trings在編程中最重要和使用的數據類型之一。 它允許計算機與世界互動和交流,例如打印指令或從用戶那里讀取輸入。 操縱和組合字符串的能力使程序員能夠處理和處理文本,例如,從網站表單中提取用戶輸入,從處理后的文本中提取數據,并使用該數據執行諸如情感分析之類的活動。 情感分析是自然語言處理的一個子領域,它使計算機可以根據一段文本對情緒(消極,積極或中立)進行分類。
“All sentiment is right; because sentiment has a reference to nothing beyond itself, and is always real, wherever a man is conscious of it.” — David Hume
“所有觀點都是正確的; 因為情感無處不在,而無論男人意識到什么,情感總是真實的。” —大衛·休ume
Python is one of the main programming languages used to analyze and manipulate data next to R. Python is used in data analytics to help access databases and communicate with them. It is also useful in importing and exporting data using different web scraping techniques. Once this data is obtained, Python is used to clean and prepare data sets before they are fed to a machine-learning algorithm.
Python是用于分析和處理R之后的數據的主要編程語言之一。Python用于數據分析以幫助訪問數據庫并與它們進行通信。 在使用不同的Web抓取技術導入和導出數據時,它也很有用。 一旦獲得了這些數據,就可以使用Python清理并準備數據集,然后再將其饋送到機器學習算法中。
There are five ways you can use Python to format strings: formatting strings using the modulo operator, formatting using Python’s built-in format function, formatting using Python 3.7 f-strings, formatting manually, and finally using template strings. We will cover each one of these methods as well as when to use each of them.
使用Python格式化字符串的方法有五種:使用模運算符格式化字符串,使用Python的內置格式化函數格式化,使用Python 3.7 f字符串格式化, 手動格式化以及最后使用模板字符串。 我們將介紹這些方法中的每一種以及何時使用它們。
Let’s get right to it…
讓我們開始吧...
使用模運算符 (Using the modulo operator)

If you wrote code using C or C++ before, this would look very familiar to you. In Python, we can use the modulo operator (%) to perform simple positional formatting. What I call placeHolder here, represents the control specs for formatting and converting the string. The % tells the interpreter that the following characters are the rules for converting the string. The conversion rules include information about the desired width of the result formatted string, the type of the result, and the precision of it — in case of floats.
如果您以前使用C或C ++編寫代碼,那么您會覺得很熟悉。 在Python中,我們可以使用模運算符(%)進行簡單的位置格式設置。 我在這里所謂的placeHolder代表用于格式化和轉換字符串的控件規范。 %告訴解釋器以下字符是轉換字符串的規則。 轉換規則包括有關結果格式字符串的所需寬度,結果類型及其精度(如果是浮點數)的信息。

This type of string formatting is sometimes referred to as the “old style” formatting. The placeHolder can refer to values directly or can be specified using keywords arguments.
這種類型的字符串格式有時稱為“舊樣式”格式。 placeHolder可以直接引用值,也可以使用關鍵字參數指定。
formatted_str = 'Yesterday I bought %d %s for only %.2f$!' % (10, 2'bananas',2.6743)
If we try to print this string, we will get Yesterday I bought 10 bananas for only 2.67$!
.
如果我們嘗試打印此字符串,我們將得到Yesterday I bought 10 bananas for only 2.67$!
。
As you can see here, I had three placeHolders for three values, the first integer, the string — bananas — and the price of the bananas, which is a float. When referring to the float, I decided that a precision of two is all I needed; that’s why only 67 is displayed after the decimal point.
如您在這里看到的,我為三個值設置了三個placeHolders ,它們是第一個整數 , 字符串 -bananas和香蕉的價格,即float 。 當提到浮點數時,我決定只需要2的精度即可。 這就是為什么小數點后僅顯示67。
In the previous example, we replaced the placeHolders with the values directly. There is another way we can achieve this mapping, which is through using keyword arguments or by passing a dictionary.
在前面的示例中,我們直接用值替換了placeHolders 。 我們可以通過使用關鍵字參數或通過傳遞字典來實現此映射的另一種方法。
name = 'John'
balance = 235765
formatted_str = 'Hello %(name)s, your current balance is %(balance)6.0f dollars.' % {"name":name, "balance":balance}
Using this method, we need to use the {}
instead of the ()
. Because of that, we can also use a dictionary directly to fill in the placeHolders.
使用此方法,我們需要使用{}
而不是()
。 因此,我們還可以直接使用字典來填充placeHolders 。
dictionary = {'quantity': 10, 'name': 'bananas', 'price': 2.6743}
formatted_str = 'I got %(quantity)d %(name)s for $%(price).2f$' % dictionary
The complete code for this section:
本節的完整代碼:
使用格式化方法 (Using the format method)

In Python 3, a new method to regulate the % operator syntax was introduced to the language. This is done using the built-in format method, also known as the “new style” formatting. Using the format method has many commonalities with using the % operator. Let’s consider rewriting some of the examples from before:
在Python 3中,該語言引入了一種用于調節%運算符語法的新方法。 這是使用內置的格式化方法(也稱為“新樣式”格式化)完成的。 使用格式方法與使用%運算符有許多共性。 讓我們考慮重寫之前的一些示例:
name = 'John'
balance = 235765
formatted_str = 'Hello %(name)s, your current balance is %(balance)6.0f dollars.' % {"name":name, "balance":balance}
Will become:
會變成:
name = 'John'
balance = 235765
formatted_str = 'Hello {name:s}, your current balance is {balance:6.0f} dollars.'.format("name":name, "balance":balance)
We can summarize the differences between the % operator syntax and the format method as:
我們可以將%運算符語法和format方法的區別總結為:
Using the % operator, we use the
()
inside the string, while with format method we use{}
.使用%運算符,我們在字符串內部使用
()
,而使用format方法,則使用{}
。To define the type of the conversion in the % operator, we set it right after the %, while in the format function we set the conversion after
:
inside the{}
.要在%運算符中定義轉換的類型,我們將其設置在%之后,而在format函數中,將轉換設置在以下位置
:
{}
。
However, if we want to pass a dictionary to the format string, we will need to modify the reforestation slightly. Instead of passing the name of the dictionary, we need to pass a pointer to the dictionary, for example:
但是,如果我們想將字典傳遞給格式字符串,則需要稍作修改。 除了傳遞字典名稱之外,我們還需要傳遞一個指向字典的指針,例如:
dictionary = {'quantity': 10, 'name': 'bananas', 'price': 2.6743}
formatted_str = 'I got {quantity:d} {name:s} for {price:.2f}$'.format(**dictionary)
Moreover, we can use the same conversion rules of the % operator that can be used in the format method as well. In Python 3 and up to 3.6, the format method is preferred to the % operator approach. The format method presented a powerful approach to format strings; it didn’t complicate the simple case — such as the examples above — but, at the same time providing new levels to how we format strings.
此外,我們可以使用%運算符的轉換規則,該轉換規則也可以在format方法中使用。 在Python 3和3.6以下版本中,format方法優于%運算符方法。 格式化方法提供了一種強大的格式化字符串的方法。 它并沒有使簡單的情況(例如上面的示例)復雜化,但是同時為我們格式化字符串的方式提供了新的層次 。
The complete code for this section:
本節的完整代碼:
使用f弦 (Using f-strings)

This, in my opinion, the fanciest and most elegant method to format strings. The f-string was presented in Python 3.8 as a more straightforward approach to string formating. Before we get into f-strings, let’s quickly cover the three types of strings in Python 3.8 and up.
我認為,這是格式化字符串的最簡單,最優雅的方法。 f字符串在Python 3.8中提出,是一種更簡單的字符串格式化方法。 在介紹f字符串之前,讓我們快速介紹一下Python 3.8及更高版本中的三種字符串。
Normal/ standard strings: contained between “” or ‘’, example
“Hello, world!”
. These are the most commonly used string type.普通/標準字符串:包含在“”或“”之間,例如
“Hello, world!”
。 這些是最常用的字符串類型。Raw strings: lead by r”, for example
r’hello\nworld’
. In this type of strings, no processing is done on the string. Which means, escape characters don't work in these strings. Instead, they will be printed without any processing. This type of strings is mostly used in regular expressions.原始字符串 :以r“
r'hello\nworld'
,例如r'hello\nworld'
。 在這種類型的字符串中,不對字符串進行任何處理。 這意味著轉義字符在這些字符串中不起作用。 取而代之的是,將不進行任何處理就打印它們。 這種類型的字符串通常用于正則表達式中。f-strings: lead by f”, for example,
f’hello John!’
. F-strings as used as an alternative way to format strings.f弦:以f
f'hello John!'
,例如f'hello John!'
。 F字符串用作格式化字符串的替代方法。
f-strings present a simple way to format strings by directly embedding expression into the string. Let’s revisit the examples from before, one more time.
f字符串提供了一種通過直接將表達式直接嵌入到字符串中來格式化字符串的簡單方法。 讓我們再回顧一次以前的示例。
name = 'John'
balance = 235765
formatted_str = 'Hello {name:s}, your current balance is {balance:6.0f} dollars.'.format("name":name, "balance":balance)
If we want to rewrite this formatting using f-strings, it will look like:
如果我們想使用f字符串重寫此格式,則它將類似于:
name = 'John'
balance = 235765
formatted_str = f'Hello {name}, your current balance is {balance} dollars.'
One way f-string simplifies string formatting is, we can directly pass iterables — dictionaries, lists, etc. — to the string, as follows:
f字符串簡化字符串格式的一種方法是,我們可以將可迭代對象(字典,列表等)直接傳遞給字符串,如下所示:
dictionary = {'quantity': 10, 'name': 'bananas', 'price': 2.6743}
formatted_str = f'I got dictionary[quantity] dictionary[name] for dictionary[price]$'#f-string with lists
myList = [1,2,3,4]
formatted_str = f'The last item of the list is myList[-1]'
You can also perform simple arithmetic or logic operations within an f-string directly.
您還可以直接在f字符串中執行簡單的算術或邏輯運算。
#Arithmetic
myList = [1,2,3,4]
formatted_str = f'The sum of the last and first items of the list is myList[0] + myList[-1]'
#Logic
formatted_str = f'myList[0] == myList[-1]'
f-strings provide much more freedom to the options we can use inside the string we want to format, such as list indexing, calling list or dictionary methods, or general iterables functions — e.g., len
, sum
, min
, and max
. We can also use conditional statements in an f-string:
f字符串為我們可以在要格式化的字符串中使用的選項提供了更大的自由度,例如列表索引,調用列表或字典方法或常規的可迭代函數(例如len
, sum
, min
和max
。 我們還可以在f字符串中使用條件語句:
age = 21
formatted_str = f'You
The complete code for this section:
本節的完整代碼:
手動格式化 (Manual Formatting)
Manual formatting refers to using standard string methods to format strings. Mostly, we use the rjust
, ljust
, and center
to justify the strings. The rjust
method right-justifies a string given a specific width by padding it with spaces on the left. The ljust
adds padding to the right and the center
method adds padding on both sides of the string. These methods do not modify the original string; they instead return a new modified string. There is another string method that can be used to format strings, which is the zfill
method. This method pads a string with a numeric value with zeros on the left.
手動格式化是指使用標準字符串方法來格式化字符串。 通常,我們使用rjust
, ljust
和center
來對齊字符串。 rjust
方法通過在字符串左側填充空格來對指定寬度的字符串進行右對齊。 ljust
會在右邊添加填充,而center
方法會在字符串的兩側添加填充。 這些方法不修改原始字符串。 相反,它們返回一個新的修改后的字符串。 還有另一種可用于格式化字符串的字符串方法,即zfill
方法。 此方法用左邊的零填充數字值的字符串。
使用模板字符串 (Using template strings)

Template strings are an alternative to the % operator, but instead of the %, template strings use the $ sign. Both methods provide what we refer to as substitution formatting. Template strings are not built-in in Python, hence to use them, we need to first import the string
module. Template strings have three rules:
模板字符串是%運算符的替代方法,但是模板字符串使用$符號代替%。 兩種方法都提供了我們稱為替代格式的內容。 模板字符串不是Python內置的,因此要使用它們,我們需要首先導入string
模塊。 模板字符串具有三個規則:
$$
is an escape character.$$
是轉義字符。Whatever follows the
$
sign directly is the placeHolder for the template. By default, these placeHolders are restricted to any case-insensitive alphanumeric string. The first non-placeHolder character after the $ sign terminates this placeHolder specs, for example, a whitespace character.直接在
$
符號后面的是模板的placeHolder 。 默認情況下,這些placeHolders限于任何不區分大小寫的字母數字字符串。 $符號后的第一個非placeHolder字符終止了該placeHolder規范,例如,空白字符。
These rules ad more are already defined in the string module, so once imported, you can go ahead and use them without the need to define them.
字符串模塊中已經定義了這些規則,因此,一旦導入,您就可以繼續使用它們而無需定義它們。
The template string has two main methods: the substitute
method and the safe_substitute
method. Both methods take the same argument, which is the substitute mapping. Moreover, both methods return a new formatted string, you can think of the template object as the blueprint for how future strings will be formatted. For example:
模板字符串有兩個主要方法: substitute
方法和safe_substitute
方法。 兩種方法都采用相同的參數,即替代映射。 而且,這兩種方法都返回一個新的格式化字符串,您可以將模板對象視為將來如何格式化字符串的藍圖。 例如:
from string import Template
formatted_str = Template('Hello $who, your current balance is $how dollars.')
formatted_str.substitute(who='John', how=235765)
To see the difference between the substitute and the safe_substitute methods, let’s try using a dictionary as our substitution mapping.
要查看替代方法和safe_substititute方法之間的區別,讓我們嘗試使用字典作為替代映射。
from string import Template
mapping = dict(who='John', how=235765)
formatted_str = Template('Hello $who, your current balance is $how dollars.')
Returned_str = formatted_str.substitute(mapping)
Assume our dictionary doesn’t have all the keys we need for the mapping, using the substitute
method will give a keyError. Here's where safe_substitute
comes to the help, if this method didn't find the correct key, it will return a string with the placeHolder for the wrong key. For example, this code:
假設我們的字典沒有我們映射所需的所有鍵,那么使用substitute
方法將給出一個keyError 。 這是safe_substitute
提供幫助的地方,如果此方法找不到正確的密鑰,它將為錯誤的密鑰返回一個帶有placeHolder的字符串。 例如,此代碼:
from string import Template
mapping = dict(who='John')
formatted_str = Template('Hello $who, your current balance is $how dollars.')
Returned_str = formatted_str.safe_substitute(mapping)
Will return Hello John, your current balance is $how dollars.
where if I had used the substitute
method, I would've gotten an error.
將返回Hello John, your current balance is $how dollars.
如果我使用了substitute
方法,那我會得到一個錯誤。
The complete code for this section:
本節的完整代碼:
結論 (Conclusion)
In this article, we covered five different ways you can use to format a string in Python:
在本文中,我們介紹了可用于在Python中格式化字符串的五種不同方式:
- The modulo operator. 模運算符。
- The format function. 格式功能。
- f-strings. F弦。
- Manual formatting. 手動格式化。
- Template strings. 模板字符串。
Each method has its usage advantages and disadvantages. A general rule of thumb, as put by Dan Badar, if the string you’re formatting is user-obtained, template strings are the way to go. If not, use f-strings if you’re on Python 3.7 or the format function elsewhere.
每種方法都有其使用的優缺點。 根據Dan Badar的一般經驗法則,如果要格式化的字符串是用戶獲得的,則使用模板字符串是可行的方法。 否則,如果您使用的是Python 3.7或其他地方的format函數,請使用f字符串。
翻譯自: https://towardsdatascience.com/a-guide-to-everything-string-formatting-in-python-e724f101eac5
python中格式化字符串
本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。 如若轉載,請注明出處:http://www.pswp.cn/news/389453.shtml 繁體地址,請注明出處:http://hk.pswp.cn/news/389453.shtml 英文地址,請注明出處:http://en.pswp.cn/news/389453.shtml
如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!