pythonlistextract

Pythonic way to extract region name from zone (AWS/GCloud)


I'm new to Python and I was wondering, what is the best way to extract the region's name from a zone name.

For example:

GCP:

 - us-east1-c
 - europe-west2-b

AWS:

 - eu-west-2
 - ap-northeast-1

In bash, I would use:

echo "zone"|rev|cut -f2- -d-|rev"

In Python, I used:

'-'.join(zone.split('-')[:-1]),

I know it doesn't really matter, but I would like to do it in the pythonic way.

Thanks in advance!

Oh, expected output is if zone is us-east1-b

us-east1


Solution

  • I think this is enough using rsplit:

    zone = 'us-east1-b'
    print(zone.rsplit('-', 1)[0])
    # us-east1
    

    Or simply split will do:

    zone = 'us-east1-b'
    lst = zone.split('-')
    print("{}-{}".format(lst[0], lst[1]))
    # us-east1