python语法截断字符串_Python 3的f字符串:改进的字符串格式语法(指南)

python语法截断字符串

As of Python 3.6, f-strings are a great new way to format strings. Not only are they more readable, more concise, and less prone to error than other ways of formatting, but they are also faster!

从Python 3.6开始,f字符串是格式化字符串的一种很棒的新方法。 与其他格式化方式相比,它们不仅更具可读性,更简洁且不易出错,而且速度更快!

By the end of this article, you will learn how and why to start using f-strings today.

到本文结尾,您将学习如何以及为什么今天开始使用f弦。

But first, here’s what life was like before f-strings, back when you had to walk to school uphill both ways in the snow.

但是首先,这就是f弦之前的生活,那是当你不得不在雪地上双路上学的时候。

Free PDF Download: Python 3 Cheat Sheet

免费PDF下载: Python 3备忘单

Python中的“老式”字符串格式 (“Old-school” String Formatting in Python)

Before Python 3.6, you had two main ways of embedding Python expressions inside string literals for formatting: %-formatting and str.format(). You’re about to see how to use them and what their limitations are.

在Python 3.6之前,您有两种将Python表达式嵌入到字符串文字中进行格式化的主要方法:%-formatting和str.format() 。 您将了解如何使用它们以及它们的局限性。

选项1:%格式 (Option #1: %-formatting)

This is the OG of Python formatting and has been in the language since the very beginning. You can read more in the Python docs. Keep in mind that %-formatting is not recommended by the docs, which contain the following note:

这是Python格式的OG,从一开始就使用该语言。 您可以在Python文档中阅读更多内容。 请记住,文档不建议使用%格式,其中包含以下注意事项:

“The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly).

“这里描述的格式化操作表现出各种古怪,导致许多常见错误(例如未能正确显示元组和字典)。

Using the newer formatted string literals or the str.format() interface helps avoid these errors. These alternatives also provide more powerful, flexible and extensible approaches to formatting text.” (Source)

使用较新的格式化字符串文字或str.format()接口有助于避免这些错误。 这些替代方案还提供了更强大,灵活和可扩展的文本格式设置方法。” ( 来源

如何使用%格式 (How to Use %-formatting)

String objects have a built-in operation using the % operator, which you can use to format strings. Here’s what that looks like in practice:

字符串对象具有使用%运算符的内置操作,可用于格式化字符串。 这是实际的情况:

 >>> >>>  name name = = "Eric"
"Eric"
>>> >>>  "Hello, "Hello,  %s%s ." ." % % name
name
'Hello, Eric.'
'Hello, Eric.'

In order to insert more than one variable, you must use a tuple of those variables. Here’s how you would do that:

为了插入多个变量,必须使用这些变量的元组。 这样做的方法如下:

为什么%格式不好 (Why %-formatting Isn’t Great)

The code examples that you just saw above are readable enough. However, once you start using several parameters and longer strings, your code will quickly become much less easily readable. Things are starting to look a little messy already:

您上面看到的代码示例可读性强。 但是,一旦开始使用多个参数和更长的字符串,您的代码将很快变得不那么易读。 事情已经开始看起来有些混乱:

 >>> >>>  first_name first_name = = "Eric"
"Eric"
>>> >>>  last_name last_name = = "Idle"
"Idle"
>>> >>>  age age = = 74
74
>>> >>>  profession profession = = "comedian"
"comedian"
>>> >>>  affiliation affiliation = = "Monty Python"
"Monty Python"
>>> >>>  "Hello, "Hello,  %s%s    %s%s . You are . You are  %s%s . You are a . You are a  %s%s . You were a member of . You were a member of  %s%s ." ." % % (( first_namefirst_name , , last_namelast_name , , ageage , , professionprofession , , affiliationaffiliation )
)
'Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.'
'Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.'

Unfortunately, this kind of formatting isn’t great because it is verbose and leads to errors, like not displaying tuples or dictionaries correctly. Fortunately, there are brighter days ahead.

不幸的是,这种格式不是很好,因为它冗长且会导致错误,例如无法正确显示元组或字典。 幸运的是,还有更美好的日子。

选项#2:str.format() (Option #2: str.format())

This newer way of getting the job done was introduced in Python 2.6. You can check out the Python docs for more info.

Python 2.6中引入了这种完成工作的新方法。 您可以查看Python文档以获取更多信息。

如何使用str.format() (How To Use str.format())

str.format()  is an improvement on %-formatting. It uses normal function call syntax and is extensible through the __format__() method on the object being converted to a string.

str.format()是%格式的改进。 它使用正常的函数调用语法,并且可以通过将__format__()方法转换为要转换为字符串的对象的方法扩展

With str.format(), the replacement fields are marked by curly braces:

使用str.format() ,替换字段用花括号标记:

You can reference variables in any order by referencing their index:

您可以通过引用变量的索引以任何顺序引用它们:

 >>> >>>  "Hello, {1}. You are {0}.""Hello, {1}. You are {0}." .. formatformat (( ageage , , namename )
)
'Hello, Eric. You are 74.'
'Hello, Eric. You are 74.'

But if you insert the variable names, you get the added perk of being able to pass objects and then reference parameters and methods in between the braces:

但是,如果您插入变量名称,则会获得额外的好处,即能够传递对象,然后在花括号之间引用参数和方法:

You can also use ** to do this neat trick with dictionaries:

您还可以使用**使用字典来完成此整洁技巧:

 >>> >>>  person person = = {{ 'name''name' : : 'Eric''Eric' , , 'age''age' : : 7474 }
}
>>> >>>  "Hello, {name}. You are {age}.""Hello, {name}. You are {age}." .. formatformat (( **** personperson )
)
'Hello, Eric. You are 74.'
'Hello, Eric. You are 74.'

str.format() is definitely an upgrade when compared with %-formatting, but it’s not all roses and sunshine.

与% str.format()相比, str.format()绝对是升级,但并不是所有的玫瑰和阳光。

为什么str.format()不好 (Why str.format() Isn’t Great)

Code using str.format() is much more easily readable than code using %-formatting, but str.format() can still be quite verbose when you are dealing with multiple parameters and longer strings. Take a look at this:

使用str.format()代码比使用% str.format()代码更易于阅读,但是当您处理多个参数和更长的字符串时, str.format()仍然很冗长。 看看这个:

If you had the variables you wanted to pass to .format() in a dictionary, then you could just unpack it with .format(**some_dict) and reference the values by key in the string, but there has got to be a better way to do this.

如果您有要在字典中传递给.format()的变量,则可以只用.format(**some_dict)解压缩.format(**some_dict)字符串中的键引用值,但是必须有更好的方法做到这一点的方法。

f字符串:一种在Python中格式化字符串的新方法和改进方法 (f-Strings: A New and Improved Way to Format Strings in Python)

The good news is that f-strings are here to save the day. They slice! They dice! They make julienne fries! Okay, they do none of those things, but they do make formatting easier. They joined the party in Python 3.6. You can read all about it in PEP 498, which was written by Eric V. Smith in August of 2015.

好消息是F弦乐在这里挽救了一天。 他们切片! 他们骰子! 他们做朱莉安薯条! 好的,它们什么都不做,但是它们确实使格式化更容易。 他们加入了Python 3.6。 您可以在2015年8月由Eric V.Smith撰写的PEP 498中阅读所有内容。

Also called “formatted string literals,” f-strings are string literals that have an f at the beginning and curly braces containing expressions that will be replaced with their values. The expressions are evaluated at runtime and then formatted using the __format__ protocol. As always, the Python docs are your friend when you want to learn more.

f字符串也称为“格式化的字符串文字”,是在开头带有f且包含用其值替换的表达式的花括号的字符串文字。 在运行时对表达式求值,然后使用__format__协议进行格式化。 与往常一样,当您想了解更多信息时, Python文档是您的朋友。

Here are some of the ways f-strings can make your life easier.

以下是f弦可以使您的生活更轻松的一些方法。

简单语法 (Simple Syntax)

The syntax is similar to the one you used with str.format() but less verbose. Look at how easily readable this is:

语法与您用于str.format()的语法相似,但较为冗长。 看看这是多么容易阅读:

 >>> >>>  name name = = "Eric"
"Eric"
>>> >>>  age age = = 74
74
>>> >>>  ff "Hello, {name}. You are {age}."
"Hello, {name}. You are {age}."
'Hello, Eric. You are 74.'
'Hello, Eric. You are 74.'

It would also be valid to use a capital letter F:

使用大写字母F也是有效的:

Do you love f-strings yet? I hope that, by the end of this article, you’ll answer >>> F"{Yes!}".

你喜欢f弦吗? 希望在本文结尾处,您将回答>>> F"{Yes!}"

Arbitray表达式 (Arbitray Expressions)

Because f-strings are evaluated at runtime, you can put any and all valid Python expressions in them. This allows you to do some nifty things.

由于f字符串是在运行时求值的,因此您可以在其中放入所有有效的Python表达式。 这使您可以做一些漂亮的事情。

You could do something pretty straightforward, like this:

您可以做一些非常简单的事情,例如:

 >>> >>>  ff "{2 * 37}"
"{2 * 37}"
'74'
'74'

But you could also call functions. Here’s an example:

但是您也可以调用函数。 这是一个例子:

You also have the option of calling a method directly:

您还可以选择直接调用方法:

 >>> >>>  ff "{name.lower()} is funny."
"{name.lower()} is funny."
'eric idle is funny.'
'eric idle is funny.'

You could even use objects created from classes with f-strings. Imagine you had the following class:

您甚至可以使用从带有f字符串的类创建的对象。 想象一下您有以下课程:

You’d be able to do this:

您将可以执行以下操作:

 >>> >>>  new_comedian new_comedian = = ComedianComedian (( "Eric""Eric" , , "Idle""Idle" , , "74""74" )
)
>>> >>>  ff "{new_comedian}"
"{new_comedian}"
'Eric Idle is 74.'
'Eric Idle is 74.'

The __str__() and __repr__() methods deal with how objects are presented as strings, so you’ll need to make sure you include at least one of those methods in your class definition. If you have to pick one, go with __repr__() because it can be used in place of __str__().

__str__()__repr__()方法处理对象如何以字符串形式显示,因此您需要确保在类定义中至少包括这些方法之一。 如果必须选择一个,请使用__repr__()因为它可以代替__str__()

The string returned by __str__() is the informal string representation of an object and should be readable. The string returned by __repr__() is the official representation and should be unambiguous. Calling str() and repr() is preferable to using __str__() and __repr__() directly.

__str__()返回的字符串是对象的非正式字符串表示形式,应可读。 __repr__()返回的字符串是正式表示形式,应明确。 与直接使用__str__()__repr__()调用str()repr()更可取。

By default, f-strings will use __str__(), but you can make sure they use __repr__() if you include the conversion flag !r:

默认情况下,f字符串将使用__str__() ,但是如果包含转换标志!r则可以确保它们使用__repr__()

If you’d like to read some of the conversation that resulted in f-strings supporting full Python expressions, you can do so here.

如果您想阅读一些导致f字符串支持完整Python表达式的对话,则可以在此处进行

多线f弦 (Multiline f-strings)

You can have multiline strings:

您可以使用多行字符串:

 >>> >>>  name name = = "Eric"
"Eric"
>>> >>>  profession profession = = "comedian"
"comedian"
>>> >>>  affiliation affiliation = = "Monty Python"
"Monty Python"
>>> >>>  message message = = (
(
...     ...     ff "Hi {name}. "
"Hi {name}. "
...     ...     ff "You are a {profession}. "
"You are a {profession}. "
...     ...     ff "You were in {affiliation}."
"You were in {affiliation}."
... ...  )
)
>>> >>>  message
message
'Hi Eric. You are a comedian. You were in Monty Python.'
'Hi Eric. You are a comedian. You were in Monty Python.'

But remember that you need to place an f in front of each line of a multiline string. The following code won’t work:

但是请记住,您需要在多行字符串的每一行前面放置一个f 。 以下代码不起作用:

If you don’t put an f in front of each individual line, then you’ll just have regular, old, garden-variety strings and not shiny, new, fancy f-strings.

如果您没有在每行的前面加上f ,那么您将只有规则的,古老的,花园风格的琴弦,而不是闪亮的,新颖的,花哨的f琴弦。

If you want to spread strings over multiple lines, you also have the option of escaping a return with a :

如果您想将字符串分布在多行中,还可以选择使用

 >>> >>>  message message = = ff "Hi {name}. " 
"Hi {name}. " 
...           ...           ff "You are a {profession}. " 
"You are a {profession}. " 
...           ...           ff "You were in {affiliation}."
"You were in {affiliation}."
...
...
>>> >>>  message
message
'Hi Eric. You are a comedian. You were in Monty Python.'
'Hi Eric. You are a comedian. You were in Monty Python.'

But this is what will happen if you use """:

但是,如果使用"""将会发生以下情况:

Read up on indentation guidelines in PEP 8.

阅读PEP 8中的缩进准则。

速度 (Speed)

The f in f-strings may as well stand for “fast.”

f字符串中的f也可能代表“快速”。

f-strings are faster than both %-formatting and str.format(). As you already saw, f-strings are expressions evaluated at runtime rather than constant values. Here’s an excerpt from the docs:

f字符串比% str.format()str.format() 。 如您所见,f字符串是在运行时求值的表达式,而不是常量值。 这是摘录自文档:

“F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with f, which contains expressions inside braces. The expressions are replaced with their values.” (Source)

“ F字符串提供了一种使用最小语法在字符串文字中嵌入表达式的方法。 应当注意,f字符串实际上是在运行时评估的表达式,而不是常数。 在Python源代码中,f字符串是文字字符串,前缀为f ,其中大括号内包含表达式。 这些表达式将替换为其值。” ( 来源

At runtime, the expression inside the curly braces is evaluated in its own scope and then put together with the string literal part of the f-string. The resulting string is then returned. That’s all it takes.

在运行时,大括号内的表达式在其自己的范围内求值,然后与f字符串的字符串文字部分放在一起。 然后返回结果字符串。 这就是全部。

Here’s a speed comparison:

这是速度比较:

 >>> >>>  import import timeit
timeit
>>> >>>  timeittimeit .. timeittimeit (( """name = "Eric"
"""name = "Eric"
age = 74
age = 74
'%s is %s.' % (name, age)""", number = 10000)
'%s is %s.' % (name, age)""", number = 10000)
0.003324444866599663
0.003324444866599663
 >>> >>>  timeittimeit .. timeittimeit (( """name = "Eric"
"""name = "Eric"
age = 74
age = 74
f'{name} is {age}.'""", number = 10000)
f'{name} is {age}.'""", number = 10000)
0.0024820892040722242
0.0024820892040722242

As you can see, f-strings come out on top.

如您所见,f弦排在最前面。

However, that wasn’t always the case. When they were first implemented, they had some speed issues and needed to be made faster than str.format(). A special BUILD_STRING opcode was introduced.

但是,情况并非总是如此。 首次实施时,它们存在一些速度问题 ,需要比str.format()更快。 引入了特殊的BUILD_STRING操作码

Python f字符串:讨厌的细节 (Python f-Strings: The Pesky Details)

Now that you’ve learned all about why f-strings are great, I’m sure you want to get out there and start using them. Here are a few details to keep in mind as you venture off into this brave new world.

既然您已经了解了为什么f弦非常好,我相信您一定会喜欢并开始使用它们。 当您冒险进入这个勇敢的新世界时,请牢记以下一些细节。

引号 (Quotation Marks)

You can use various types of quotation marks inside the expressions. Just make sure you are not using the same type of quotation mark on the outside of the f-string as you are using in the expression.

您可以在表达式内使用各种类型的引号。 只要确保您没有在表达式中使用与f字符串相同的引号即可。

This code will work:

该代码将起作用:

This code will also work:

此代码也将起作用:

 >>> >>>  ff '{"Eric Idle"}'
'{"Eric Idle"}'
'Eric Idle'
'Eric Idle'

You can also use triple quotes:

您也可以使用三引号:

 >>> >>>  ff '''Eric Idle'''
'''Eric Idle'''
'Eric Idle'
'Eric Idle'

If you find you need to use the same type of quotation mark on both the inside and the outside of the string, then you can escape with :

如果发现需要在字符串的内部和外部使用相同类型的引号,则可以使用

辞典 (Dictionaries)

Speaking of quotation marks, watch out when you are working with dictionaries. If you are going to use single quotation marks for the keys of the dictionary, then remember to make sure you’re using double quotation marks for the f-strings containing the keys.

说到引号,使用字典时要当心。 如果要对字典的键使用单引号,请记住确保对包含键的f字符串使用双引号。

This will work:

这将起作用:

 >>> >>>  comedian comedian = = {{ 'name''name' : : 'Eric Idle''Eric Idle' , , 'age''age' : : 7474 }
}
>>> >>>  ff "The comedian is {comedian['name']}, aged {comedian['age']}."
"The comedian is {comedian['name']}, aged {comedian['age']}."
The comedian is Eric Idle, aged 74.
The comedian is Eric Idle, aged 74.

But this will be a hot mess with a syntax error:

但这将是一个语法错误的混乱局面:

If you use the same type of quotation mark around the dictionary keys as you do on the outside of the f-string, then the quotation mark at the beginning the first dictionary key will be interpreted as the end of the string.

如果在字典键周围使用与在f字符串外部相同的引号类型,则第一个字典键开头的引号将被解释为字符串的结尾。

大括号 (Braces)

In order to make a brace appear in your string, you must use double braces:

为了使大括号出现在字符串中,必须使用双大括号:

 >>> >>>  ff "{{74}}"
"{{74}}"
'{ 74 }'
'{ 74 }'

Note that using triple braces will result in there being only single braces in your string:

请注意,使用三重括号将导致您的字符串中只有一个括号:

However, you can get more braces to show if you use more than triple braces:

但是,如果使用的括号多于三个,则可以显示更多的括号:

 >>> >>>  ff "{{{{74}}}}"
"{{{{74}}}}"
'{{74}}'
'{{74}}'

反斜杠 (Backslashes)

As you saw earlier, it is possible for you to use backslash escapes in the string portion of an f-string. However, you can’t use backslashes to escape in the expression part of an f-string:

如前所述,可以在f字符串的字符串部分中使用反斜杠转义符。 但是,不能在F字符串的表达式部分中使用反斜杠进行转义:

You can work around this by evaluating the expression beforehand and using the result in the f-string:

您可以通过预先计算表达式并在f字符串中使用结果来解决此问题:

 >>> >>>  name name = = "Eric Idle"
"Eric Idle"
>>> >>>  ff "{name}"
"{name}"
'Eric Idle'
'Eric Idle'

注释 (Comments)

Expressions should not include comments using the # symbol. You’ll get a syntax error:

表达式中不应包含使用#符号的注释。 您会收到语法错误:

Lambda表达式 (Lambda Expressions)

If you need to use lambda expressions, keep in mind that the way f-strings are parsed complicates matters a bit.

如果需要使用lambda表达式,请记住, 解析f字符串的方式会使问题变得复杂。

If a !, :, or } isn’t inside parentheses, braces, brackets, or a string, then it will be interpreted as the end of an expression. Since lambdas use :, this can cause some issues:

如果一个!:}不在括号,大括号,方括号或字符串内,则它将被解释为表达式的结尾。 由于lambdas使用: ,这可能会导致一些问题:

 >>> >>>  ff "{lambda x: x * 37 (2)}"
  File "{lambda x: x * 37 (2)}"
  File "<fstring>", line "<fstring>" , line 1
    1
    (( lambda lambda xx )
             )
             ^
^
SyntaxError: SyntaxError : unexpected EOF while parsing
unexpected EOF while parsing

You can work around this problem by nesting your lambdas inside parentheses:

您可以通过将lambda嵌套在括号中来解决此问题:

前进并格式化! (Go Forth and Format!)

You can still use the older ways of formatting strings, but with f-strings, you now have a more concise, readable, and convenient way that is both faster and less prone to error. Simplifying your life by using f-strings is a great reason to start using Python 3.6 if you haven’t already made the switch. (If you are still using Python 2, don’t forget that 2020 will be here soon!)

您仍然可以使用旧的格式化字符串的方法,但是使用f字符串,您现在有了更简洁,可读和方便的方法,既更快又不易出错。 如果尚未进行切换,那么使用f字符串简化生活是开始使用Python 3.6的重要原因。 (如果您仍在使用Python 2,请不要忘记2020年即将到来!)

According to the Zen of Python, when you need to decide how to do something, then “[t]here should be one– and preferably only one –obvious way to do it.” Although f-strings aren’t the only possible way for you to format strings, they are in a great position to become that one obvious way to get the job done.

根据Python Zen的说法,当您需要决定如何做某事时,那么“这应该是一种(最好只有一种)明显的方式。” 尽管f字符串不是格式化字符串的唯一可能方法,但是它们很适合成为完成工作的一种明显方式。

进一步阅读 (Further Reading)

If you’d like to read an extended discussion about string interpolation, take a look at PEP 502. Also, the PEP 536 draft has some more thoughts about the future of f-strings.

如果您想阅读有关字符串插值的扩展讨论,请查看PEP 502 。 同样, PEP 536草案对f弦的未来有更多的思考。

Free PDF Download: Python 3 Cheat Sheet

免费PDF下载: Python 3备忘单

For more fun with strings, check out the following articles:

有关字符串的更多乐趣,请查看以下文章:

Happy Pythoning!

快乐的Pythoning!

翻译自: https://www.pybloggers.com/2018/05/python-3s-f-strings-an-improved-string-formatting-syntax-guide/

python语法截断字符串

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值