简体   繁体   English

从格式化字符串内部切割字符串会产生'TypeError:字符串索引必须是整数'

[英]Slicing a string from inside a formatted string gives 'TypeError: string indices must be integers'

Shouldn't both these commands do the same thing? 两个命令不应该做同样的事情吗?

>>> "{0[0:5]}".format("lorem ipsum")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
>>> "{0}".format("lorem ipsum"[0:5])
'lorem'

The commands 命令

>>> "{0[0]}".format("lorem ipsum")
'l'

and

>>> "{0}".format("lorem ipsum"[0])
'l'

evaluate the same. 评价一样。 (I know that I can use other methods to do this, I am mainly just curious as to why it dosen't work) (我知道我可以使用其他方法来做到这一点,我主要只是好奇为什么它不起作用)

The str.format syntax is handled by the library and supports only a few “expression” syntaxes that are not the same as regular Python syntax. str.format语法由库处理,并且仅支持一些与常规Python语法不同的“表达式”语法。 For example, 例如,

"{0[foo]}".format(dict(foo=2))  # "2"

works without quotes around the dictionary key. 在字典键周围没有引号。 Of course, there are limitations from this simplicity, like not being able to refer to a key with a ] in it, or interpreting a slice, as in your example. 当然,这种简单性存在局限性 ,例如无法在其中引用带有]的键,或者在示例中解释切片。

Note that the f-strings mentioned by kendall are handled by the compiler and (fittingly) use (almost) unrestricted expression syntax . 请注意,kendall提到的f字符串由编译器处理并(适当地)使用(几乎)不受限制的表达式语法 They need that power since they lack the obvious alternative of placing those expressions in the argument list to format . 他们需要这种力量,因为他们缺乏将这些表达式放在参数列表中进行format的明显选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM