Reputation: 173
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
Upvotes: 1
Views: 219
Reputation: 43
It seems like only correct way to do it is to use regex. I've tested following example on two totally different zones, and it seems to work:
zone = "ap-southeast-1-bkk-1a"
zone2 = "us-east-1a"
region_regex = r'(.*?-\d+)'
match1 = re.match(region_regex, zone)
match2 = re.match(region_regex, zone2)
match1.group(1), match2.group(1)
# ('ap-southeast-1', 'us-east-1')
It won't make us-east1 from us-east1-b, of course. Don't know how AWS zones were named at the time you've asked the question, but now it is "us-east-1d"? If it is named this in Google Cloud,I guess you'll need some extra work to adapt the regex formula for your case and use both of them for each cloud separately.
UPD: Maybe it's a little out of context, and "ap-southeast-1-bkk" seems to be a Local Zone. But the fact of this approach works for both AZ and Local AZ makes it a more universal option.
Upvotes: 0
Reputation: 26039
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
Upvotes: 2
Reputation: 620
ok based on your comments I see String slicing
will do the work for you.
Read more about it here
Try this - print "us-east1-b"[:-2]
Upvotes: 0