def utm2mgrs(e, n, grid, zeros=0):
 square_set = (int(grid[:(-1)]) % 6)
 ew_idx = (int((e / 100000)) - 1)
 ns_idx = int(((n % 2000000) / 100000))
 ns_letters_135 = 'ABCDEFGHJKLMNPQRSTUV'
 ns_letters_246 = 'FGHJKLMNPQRSTUVABCDE'
 ew_letters_14 = 'ABCDEFGH'
 ew_letters_25 = 'JKLMNPQR'
 ew_letters_36 = 'STUVWXYZ'
 if (square_set == 1):
  square = (ew_letters_14[ew_idx] + ns_letters_135[ns_idx])
 elif (square_set == 2):
  square = (ew_letters_25[ew_idx] + ns_letters_246[ns_idx])
 elif (square_set == 3):
  square = (ew_letters_36[ew_idx] + ns_letters_135[ns_idx])
 elif (square_set == 4):
  square = (ew_letters_14[ew_idx] + ns_letters_246[ns_idx])
 elif (square_set == 5):
  square = (ew_letters_25[ew_idx] + ns_letters_135[ns_idx])
 else:
  square = (ew_letters_36[ew_idx] + ns_letters_246[ns_idx])
 easting = ('%05d' % (e % 100000))
 northing = ('%05d' % (n % 100000))
 return ' '.join([grid, square, easting[:(- zeros)], northing[:(- zeros)]])

def utm2mgrs ( e , n , grid , zeros = 0 ) : square_set = ( int ( grid [ : ( - 1 ) ] ) % 6 ) ew_idx = ( int ( ( e / 100000 ) ) - 1 ) ns_idx = int ( ( ( n % 2000000 ) / 100000 ) ) ns_letters_135 = 'ABCDEFGHJKLMNPQRSTUV' ns_letters_246 = 'FGHJKLMNPQRSTUVABCDE' ew_letters_14 = 'ABCDEFGH' ew_letters_25 = 'JKLMNPQR' ew_letters_36 = 'STUVWXYZ' if ( square_set == 1 ) : square = ( ew_letters_14 [ ew_idx ] + ns_letters_135 [ ns_idx ] ) elif ( square_set == 2 ) : square = ( ew_letters_25 [ ew_idx ] + ns_letters_246 [ ns_idx ] ) elif ( square_set == 3 ) : square = ( ew_letters_36 [ ew_idx ] + ns_letters_135 [ ns_idx ] ) elif ( square_set == 4 ) : square = ( ew_letters_14 [ ew_idx ] + ns_letters_246 [ ns_idx ] ) elif ( square_set == 5 ) : square = ( ew_letters_25 [ ew_idx ] + ns_letters_135 [ ns_idx ] ) else : square = ( ew_letters_36 [ ew_idx ] + ns_letters_246 [ ns_idx ] ) easting = ( '%05d' % ( e % 100000 ) ) northing = ( '%05d' % ( n % 100000 ) ) return ' ' . join ( [ grid , square , easting [ : ( - zeros ) ] , northing [ : ( - zeros ) ] ] )
convert utm easting/northing pair and grid zone to mgrs-style grid reference .