python中格式化字符串_Python中所有字符串格式化的指南

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)

Image for post
Canva)Canva制作 )

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代表用于格式化和轉換字符串的控件規范。 %告訴解釋器以下字符是轉換字符串的規則。 轉換規則包括有關結果格式字符串的所需寬度,結果類型及其精度(如果是浮點數)的信息。

Image for post
Canva)Canva制作 )

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)

Image for post
Canva)Canva制作 )

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方法的區別總結為:

  1. Using the % operator, we use the () inside the string, while with format method we use {} .

    使用%運算符,我們在字符串內部使用() ,而使用format方法,則使用{}

  2. 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)

Image for post
Canva)Canva制作 )

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及更高版本中的三種字符串。

  1. Normal/ standard strings: contained between “” or ‘’, example “Hello, world!”. These are the most commonly used string type.

    普通/標準字符串:包含在“”或“”之間,例如“Hello, world!” 。 這些是最常用的字符串類型。

  2. 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' 。 在這種類型的字符串中,不對字符串進行任何處理。 這意味著轉義字符在這些字符串中不起作用。 取而代之的是,將不進行任何處理就打印它們。 這種類型的字符串通常用于正則表達式中。

  3. 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字符串為我們可以在要格式化的字符串中使用的選項提供了更大的自由度,例如列表索引,調用列表或字典方法或常規的可迭代函數(例如lensumminmax 。 我們還可以在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.

手動格式化是指使用標準字符串方法來格式化字符串。 通常,我們使用rjustljustcenter來對齊字符串。 rjust方法通過在字符串左側填充空格來對指定寬度的字符串進行右對齊。 ljust會在右邊添加填充,而center方法會在字符串的兩側添加填充。 這些方法不修改原始字符串。 相反,它們返回一個新的修改后的字符串。 還有另一種可用于格式化字符串的字符串方法,即zfill方法。 此方法用左邊的零填充數字值的字符串。

使用模板字符串 (Using template strings)

Image for post
Canva)Canva制作 )

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模塊。 模板字符串具有三個規則:

  1. $$ is an escape character.

    $$是轉義字符。

  2. 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中格式化字符串的五種不同方式:

  1. The modulo operator.

    模運算符。
  2. The format function.

    格式功能。
  3. f-strings.

    F弦。
  4. Manual formatting.

    手動格式化。
  5. 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,一經查實,立即刪除!

相關文章

Javassist實現JDK動態代理

提到JDK動態代理,相信很多人并不陌生。然而,對于動態代理的實現原理,以及如何編碼實現動態代理功能,可能知道的人就比較少了。接下一來,我們就一起來看看JDK動態代理的基本原理,以及如何通過Javassist進行模…

數據圖表可視化_數據可視化如何選擇正確的圖表第1部分

數據圖表可視化According to the World Economic Forum, the world produces 2.5 quintillion bytes of data every day. With so much data, it’s become increasingly difficult to manage and make sense of it all. It would be impossible for any person to wade throug…

Keras框架:實例分割Mask R-CNN算法實現及實現

實例分割 實例分割(instance segmentation)的難點在于: 需要同時檢測出目標的位置并且對目標進行分割,所以這就需要融合目標檢測(框出目標的位置)以及語義分割(對像素進行分類,分割…

機器學習 缺陷檢測_球檢測-體育中的機器學習。

機器學習 缺陷檢測🚩 目標 (🚩Objective) We want to evaluate the quickest way to detect the ball in a sport event in order to develop an Sports AI without spending a million dollars on tech or developers. Quickly we find out that detec…

莫煩Pytorch神經網絡第二章代碼修改

import torch import numpy as np""" Numpy Torch對比課程 """ # #tensor與numpy格式數據相互轉換 # np_data np.arange(6).reshape((2,3)) # print(np_data) # # torch_data torch.from_numpy(np_data) # print(\n,torch_data) # # tensor2ar…

自定義字符類

當 VC不使用MFC,無法使用屬于MFC的CString,為此自定義一個,先暫時使用,后續完善。 頭文件: #pragma once#define MAX_LOADSTRING 100 // 最大字符數class CString {public:char *c_str, cSAr[MAX_LOADSTRING];WCHAR *w…

使用python和javascript進行數據可視化

Any data science or data analytics project can be generally described with the following steps:通常可以通過以下步驟來描述任何數據科學或數據分析項目: Acquiring a business understanding & defining the goal of a project 獲得業務理解并定義項目目…

Android 事件處理

事件就是用戶對圖形的操作,在android手機和平板電腦上,主要包含物理按鍵事件和觸摸屏事件兩類。物理按鍵事件包含:按下、抬起、長按等;觸摸屏事件主要包含按下、抬起、滾動、雙擊等。 在View中提供了onTouchEvent()方法&#xff0…

莫煩Pytorch神經網絡第三章代碼修改

3.1Regression回歸 import torch import torch.nn.functional as F from torch.autograd import Variable import matplotlib.pyplot as plt""" 創建數據 """x torch.unsqueeze(torch.linspace(-1,1,100),dim1) y x.pow(2) 0.2*torch.rand(x…

為什么餅圖有問題

介紹 (Introduction) It seems as if people are split on pie charts: either you passionately hate them, or you are indifferent. In this article, I am going to explain why pie charts are problematic and, if you fall into the latter category, what you can do w…

New Distinct Substrings(后綴數組)

New Distinct Substrings&#xff08;后綴數組&#xff09; 給定一個字符串&#xff0c;求不相同的子串的個數。\(n<50005\)。 顯然&#xff0c;任何一個子串一定是后綴上的前綴。先&#xff08;按套路&#xff09;把后綴排好序&#xff0c;對于當前的后綴\(S_i\)&#xff0…

Android dependency 'com.android.support:support-v4' has different version for the compile (26.1.0...

在項目中加入react-native-camera的時候 出現的錯誤. 解決方案: 修改 implementation project(:react-native-camera)為 implementation (project(:react-native-camera)) {exclude group: "com.android.support"}查看原文 Could not find play-services-basement.aa…

先知模型 facebook_使用Facebook先知進行犯罪率預測

先知模型 facebookTime series prediction is one of the must-know techniques for any data scientist. Questions like predicting the weather, product sales, customer visit in the shopping center, or amount of inventory to maintain, etc - all about time series …

莫煩Pytorch神經網絡第四章代碼修改

4.1CNN卷積神經網絡 import torch import torch.nn as nn from torch.autograd import Variable import torch.utils.data as Data import torchvision import matplotlib.pyplot as pltEPOCH 1 BATCH_SIZE 50 LR 0.001 DOWNLOAD_MNIST False #如果數據集已經下載到…

github gists 101使代碼共享漂亮

If you’ve been going through Medium, looking at technical articles, you’ve undoubtedly seen little windows that look like the below:如果您一直在閱讀Medium&#xff0c;并查看技術文章&#xff0c;那么您無疑會看到類似于以下內容的小窗口&#xff1a; def hello_…

loj #6278. 數列分塊入門 2

題目 題解 區間修改&#xff0c;詢問區間小于c的個數。分塊排序&#xff0c;用vector。至于那個塊的大小&#xff0c;好像要用到均值不等式 我不太會。。。就開始一個個試&#xff0c;發現sizsqrt(n)/4時最快&#xff01;&#xff01;&#xff01;明天去學一下算分塊復雜度的方…

基于Netty的百萬級推送服務設計要點

1. 背景1.1. 話題來源最近很多從事移動互聯網和物聯網開發的同學給我發郵件或者微博私信我&#xff0c;咨詢推送服務相關的問題。問題五花八門&#xff0c;在幫助大家答疑解惑的過程中&#xff0c;我也對問題進行了總結&#xff0c;大概可以歸納為如下幾類&#xff1a;1&#x…

莫煩Pytorch神經網絡第五章代碼修改

5.1動態Dynamic import torch from torch import nn import numpy as np import matplotlib.pyplot as plt# torch.manual_seed(1) # reproducible# Hyper Parameters INPUT_SIZE 1 # rnn input size / image width LR 0.02 # learning rateclass…

鮮為人知的6個黑科技網站_6種鮮為人知的熊貓繪圖工具

鮮為人知的6個黑科技網站Pandas is the go-to Python library for data analysis and manipulation. It provides numerous functions and methods that expedice the data analysis process.Pandas是用于數據分析和處理的Python庫。 它提供了加速數據分析過程的眾多功能和方法…

VRRP網關冗余

實驗要求?1、R1創建環回口&#xff0c;模擬外網?2、R2&#xff0c;R3使用VRRP技術?3、路由器之間使用EIGRP路由協議? 實驗拓撲? 實驗配置??R1(config)#interface loopback 0R1(config-if)#ip address 1.1.1.1 255.255.255.0R1(config-if)#int e0/0R1(config-if)#ip addr…