python字符串前加f,字符串太長 pep8_Python f字符串– PEP 498 –文字字符串插值

 2023-11-19 阅读 27 评论 0

摘要:字符串太長 pep8python字符串前加f?Python f-strings or formatted strings are the new way to format strings. This feature was introduced in Python 3.6 under PEP-498. It’s also called literal string interpolation. Python f字符串或格式化的字符串是格式化字符串

字符串太長 pep8

python字符串前加f?Python f-strings or formatted strings are the new way to format strings. This feature was introduced in Python 3.6 under PEP-498. It’s also called literal string interpolation.

Python f字符串或格式化的字符串是格式化字符串的新方法。 此功能是在PEP-498下的Python 3.6中引入的。 也稱為文字字符串插值

為什么我們需要F弦? (Why do we need f-strings?)

Python provides various ways to format a string. Let’s quickly look at them and what are the issues they have.

Python提供了多種格式化字符串的方法。 讓我們快速查看它們以及它們有什么問題。

  • % formatting – great for simple formatting but limited support for strings, ints, doubles only. We can’t use it with objects.

    %格式 -非常適合簡單的格式設置,但僅對string ,ints和double的支持有限。 我們不能將其與對象一起使用。
  • Template Strings – it’s very basic. Template strings work with keyword arguments like dictionary only. We are not allowed to call any function and arguments must be strings.

    模板字符串 –非常基本。 模板字符串僅可與關鍵字參數(例如字典)一起使用。 我們不允許調用任何函數,并且參數必須是字符串。
  • String format() – Python String format() function was introduced to overcome the issues and limited features of %-formatting and template strings. However, it’s too verbose. Let’s look at its verbosity with a simple example.
    >>> age = 4 * 10
    >>> 'My age is {age}.'.format(age=age)
    'My age is 40.'

    字符串格式()– Python字符串格式()函數的引入是為了克服%格式和模板字符串的問題和有限的功能。 但是,它太冗長了。 讓我們用一個簡單的例子來看看它的詳細程度。

Python f-strings works almost similar like format() function but removes all the verbosity that format() function has. Let’s see how easily we can format the above string using f-strings.

Python f字符串的工作原理幾乎類似于format()函數,但刪除了format()函數具有的所有冗長性。 讓我們看看使用f字符串格式化上述字符串的難易程度。

>>> f'My age is {age}'
'My age is 40.'

Python f-strings is introduced to have minimal syntax for string formatting. The expressions are evaluated at runtime. If you are using Python 3.6 or higher version, you should use f-strings for all your string formatting requirements.

引入Python f字符串是為了使字符串格式化的語法最少 。 在運行時對表達式求值。 如果您使用的是Python 3.6或更高版本,則應使用f-strings滿足所有字符串格式要求。

Python f字符串示例 (Python f-strings examples)

Let’s look at a simple example of f-strings.

讓我們看一個簡單的f字符串示例。

name = 'Pankaj'
age = 34f_string = f'My Name is {name} and my age is {age}'print(f_string)
print(F'My Name is {name} and my age is {age}')  # f and F are samename = 'David'
age = 40# f_string is already evaluated and won't change now
print(f_string)

Output:

輸出:

My Name is Pankaj and my age is 34
My Name is Pankaj and my age is 34
My Name is Pankaj and my age is 34

Python executes statements one by one and once f-string expressions are evaluated, they don’t change even if the expression value changes. That’s why in the above code snippets, f_string value remains same even after ‘name’ and ‘age’ variable has changed in the latter part of the program.

Python會一一執行語句,并且一旦評估了f字符串表達式,即使表達式值更改,它們也不會更改。 這就是為什么在上面的代碼段中,即使在程序的后半部分更改了“ name”和“ age”變量后,f_string值仍保持不變。

1.帶表達式和轉換的f字符串 (1. f-strings with expressions and conversions)

We can use f-strings to convert datetime to a specific format. We can also run mathematical expressions in f-strings.

我們可以使用f字符串將日期時間轉換為特定格式。 我們還可以在f字符串中運行數學表達式。

from datetime import datetimename = 'David'
age = 40
d = datetime.now()print(f'Age after five years will be {age+5}')  # age = 40
print(f'Name with quotes = {name!r}')  # name = David
print(f'Default Formatted Date = {d}')
print(f'Custom Formatted Date = {d:%m/%d/%Y}')

Output:

輸出:

Age after five years will be 45
Name with quotes = 'David'
Default Formatted Date = 2018-10-10 11:47:12.818831
Custom Formatted Date = 10/10/2018

2. f字符串支持原始字符串 (2. f-strings support raw strings)

We can create raw strings using f-strings too.

我們也可以使用f字符串創建原始字符串。

print(f'Default Formatted Date:\n{d}')
print(fr'Default Formatted Date:\n {d}')

Output:

輸出:

Default Formatted Date:
2018-10-10 11:47:12.818831
Default Formatted Date:\n 2018-10-10 11:47:12.818831

3.具有對象和屬性的f字符串 (3. f-strings with objects and attributes)

We can access object attributes too in f-strings.

我們也可以在f字符串中訪問對象屬性。

class Employee:id = 0name = ''def __init__(self, i, n):self.id = iself.name = ndef __str__(self):return f'E[id={self.id}, name={self.name}]'emp = Employee(10, 'Pankaj')
print(emp)print(f'Employee: {emp}\nName is {emp.name} and id is {emp.id}')

Output:

輸出:

E[id=10, name=Pankaj]
Employee: E[id=10, name=Pankaj]
Name is Pankaj and id is 10

4. f字符串調用函數 (4. f-strings calling functions)

We can call functions in f-strings formatting too.

我們也可以用f字符串格式調用函數。

def add(x, y):return x + yprint(f'Sum(10,20) = {add(10, 20)}')

Output: Sum(10,20) = 30

輸出: Sum(10,20) = 30

5.帶空格的f字符串 (5. f-string with whitespaces)

If there are leading or trailing whitespaces in the expression, they are ignored. If the literal string part contains whitespaces then they are preserved.

如果表達式中存在前導或尾隨空格,則將其忽略。 如果文字字符串部分包含空格,則將保留它們。

>>> age = 4 * 20
>>> f'   Age = {  age   }  '
'   Age = 80  '

6.帶f字符串的Lambda表達式 (6. Lambda expressions with f-strings)

We can use lambda expressions insidef-string expressions too.

我們也可以在字符串表達式內部使用lambda表達式 。

x = -20.45
print(f'Lambda Example: {(lambda x: abs(x)) (x)}')print(f'Lambda Square Example: {(lambda x: pow(x, 2)) (5)}')

Output:

輸出:

Lambda Example: 20.45
Lambda Square Example: 25

7. f弦的其他示例 (7. f-strings miscellaneous examples)

Let’s look at some miscellaneous examples of Python f-strings.

讓我們看一些Python f字符串的其他示例。

print(f'{"quoted string"}')
print(f'{{ {4*10} }}')
print(f'{{{4*10}}}')

Output:

輸出:

quoted string
{ 40 }
{40}

That’s all for python formatted strings aka f-strings.

這就是python格式的字符串,又稱f字符串。

GitHub Repository.GitHub存儲庫中檢出完整的python腳本和更多Python示例。

Reference: PEP-498, Official Documentation

參考: PEP-498 , 官方文檔

翻譯自: https://www.journaldev.com/23592/python-f-strings-literal-string-interpolation

字符串太長 pep8

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/183323.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息