python从字符串创建切片对象 [英] python create slice object from string
本文介绍了python从字符串创建切片对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从字符串创建切片对象;现在唯一的方法似乎通过一个繁琐的hacky评估声明
I'd like to create a slice object from a string; right now the only way seems through a cumbersome hacky eval statement
class getslice:
def __getitem__(self, idx): return idx[0]
eval("getslice()[%s, 1]" %(":-1"))
提前感谢。
编辑:抱歉,如果原始提示不清楚,输入在这种情况下是:-1。关键在于解析字符串。 Ignacio Vazquez-Abrams的回答至少解决了这个问题(并且似乎也适用于反向索引),但我认为如果不是概念上干净的话,上面的解决方案仍然更加清晰(如果Python改变切片语法,它将正常工作)。 / p>
Edit: Sorry if the original prompt was not clear, the input in this case was ":-1". The point was to parse the string. Ignacio Vazquez-Abrams's response at least solved the problem (and seems to work with reverse indexing as well), but I think my solution above is still more clear if not conceptually clean (and will work correctly if Python ever changes slicing syntax).
推荐答案
slice(*[{True: lambda n: None, False: int}[x == ''](x) for x in (mystring.split(':') + ['', '', ''])[:3]])
这篇关于python从字符串创建切片对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文