字符串太长 pep8_Python f字符串– PEP 498 –文字字符串插值

字符串太长 pep8

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 = 34

f_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 same

name = '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 datetime

name = '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 = 0
    name = ''

    def __init__(self, i, n):
        self.id = i
        self.name = n

    def __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 + y


print(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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值