简体   繁体   English

从多个字符串中提取Python

[英]Python strip from multiple strings

I have list of amazon ip address which are formatted like "ip-xxxx.ap-southeast-1.compu" and like this "ip-xxxx.ec2.internal". 我有格式为“ ip-xxxx.ap-southeast-1.compu”和“ ip-xxxx.ec2.internal”的亚马逊ip地址列表。 I want to strip ".ap-southeast-1.compu" and ".ec2.internal" from ip address. 我想从IP地址中删除“ .ap-southeast-1.compu”和“ .ec2.internal”。 I want to have ip address only (like ip-xxxx). 我只想拥有IP地址(例如ip-xxxx)。 I have tried rstrip but I am not finding way of giving multiple strings for rstrip. 我已经尝试过rstrip,但没有找到为rstrip提供多个字符串的方法。 It should strip ip address if it finds ".ap-southeast-1.compu" or ".ec2.internal". 如果找到“ .ap-southeast-1.compu”或“ .ec2.internal”,则应删除IP地址。

Please Let me know how this can be handled in python. 请让我知道如何用python处理。

You can use string split function to split by dot char: 您可以使用字符串split功能按点字符拆分:

>>> ip = "ip-x-x-x-x.ap-southeast-1.compu"
>>> ip.split('.')[0]
'ip-x-x-x-x'

Might not be the most efficient way but I am a regular expression fan so figured I would show how to do it that way. 可能不是最有效的方法,但我是一个正则表达式爱好者,因此我想我将向您展示如何这样做。

import re
NewIPs = []
regex = re.compile('(ip-\d*-\d*-\d*-\d*)')
for ip in IPList:
    NewIps.append(regex.search(ip).group(1))

That will go through your list of ips and fill a new list with the ips minus the endings. 这将遍历您的ips列表,并用ips减去结尾填充新列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM