pythonsliceturbo-pascal

Is there a python equivalent of ['A'..'Z'] in turbo pascal


Like the topic, is there a (quick) way, possibly a notation, to achieve the same effect as in turbo pascal to rapid make a list of all elements containing and between 'A' and 'Z'.

In turbo pascal it could be written as ['A'..'Z']


Solution

  • You can use map on a range of character numbers:

    *letters, = map(chr,range(65,91)) # A-Z
    
    print(letters)
    
    ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
     'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    

    You can combine multiple ranges using unpacking:

    *alphanum, = *map(chr,range(65,91)), *"0123456789", *map(chr,range(97,122))
    

    Alternatively you could create a shorthand function of you own:

    def CHR(a,*b):
        return [*map(chr,range(ord(a[0]),ord(a[-1])+1))] + (CHR(*b) if b else [])
    

    Which you can reuse as needed:

    codeChars = CHR('A..Z','-','0..9')
    
    print(codeChars)
    
    ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
     'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
     'Y', 'Z', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8',
     '9']