How should I handle inclusive ranges in Python?

后端 未结 12 2229
天涯浪人
天涯浪人 2020-12-14 05:56

I am working in a domain in which ranges are conventionally described inclusively. I have human-readable descriptions such as from A to B , which represent rang

12条回答
  •  眼角桃花
    2020-12-14 06:24

    Since in Python, the ending index is always exclusive, it's worth considering to always use the "Python-convention" values internally. This way, you will save yourself from mixing up the two in your code.

    Only ever deal with the "external representation" through dedicated conversion subroutines:

    def text2range(text):
        m = re.match(r"from (\d+) to (\d+)",text)
        start,end = int(m.groups(1)),int(m.groups(2))+1
    
    def range2text(start,end):
        print "from %d to %d"%(start,end-1)
    

    Alternatively, you can mark the variables holding the "unusual" representation with the true Hungarian notation.

提交回复
热议问题