Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在string.format内使用字符串切片_Python - Fatal编程技术网

Python 如何在string.format内使用字符串切片

Python 如何在string.format内使用字符串切片,python,Python,如何在string.format中执行变量字符串切片,如下所示 "{0[:2]} Some text {0[2:4]} some text".format("123456") 结果我想要这样的结果 "{0[:2]} Some text {0[2:4]} some text".format("123456") 12一些文本34一些文本 你不能。您所能做的最好的事情是限制打印字符串的字符数(大致相当于指定一个切片结束),但不能指定任意的开始或结束索引 将数据保存到命名变量,并将切片传递到form

如何在
string.format
中执行变量字符串切片,如下所示

"{0[:2]} Some text {0[2:4]} some text".format("123456")
结果我想要这样的结果

"{0[:2]} Some text {0[2:4]} some text".format("123456")
12一些文本34一些文本


你不能。您所能做的最好的事情是限制打印字符串的字符数(大致相当于指定一个切片结束),但不能指定任意的开始或结束索引

将数据保存到命名变量,并将切片传递到
format
方法,这样更可读、更直观,解析器在错误发生时更容易识别错误:

mystr = "123456"
"{} Some text {} some text".format(mystr[:2], mystr[2:4])
如果您真的愿意,您可以将部分工作从该字符串转移到格式字符串,但这并不是一个巨大的改进(事实上,当最终需要切片时,需要更大的临时性):


为什么不简单的
“一些文本{0}一些文本”。格式(“123456”[2:4])
?请查看编辑。实际的最终字符串有点复杂。