问题描述
我想用 str.format
实现以下目标:
I want to achieve the following with str.format
:
x,y = 1234,5678
print str(x)[2:] + str(y)[:2]
我能做到的唯一方法是:
The only way I was able to do it was:
print '{0}{1}'.format(str(x)[2:],str(y)[:2])
现在,这是一个示例,我真正拥有的是一个又长又乱的字符串,因此我想将切片放在 {}
中.我研究了文档,但我不知道正确的语法.我的问题是:是否可以在替换字段内对字符串进行切片?
Now, this an example and what I really have is a long and messy string, and so I want to put slicing inside the {}
. I've studied the docs, but I can't figure out the correct syntax. My question is: is it possible to slice strings inside a replacement field?
推荐答案
不,您不能对替换字段内的字符串应用切片.
No, you can't apply slicing to strings inside a the replacement field.
您需要参考格式规范迷你语言;它定义了是什么是可能的.这种迷你语言定义了如何格式化引用的值(替换字段语法中 :
之后的部分).
You'll need to refer to the Format Specification Mini-Language; it defines what is possible. This mini language defines how you format the referenced value (the part after the :
in the replacement field syntax).
这篇关于在 str.format 中切片字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!