strip()命令剥离过多

问题描述 投票:0回答:2

我需要使用strip获取AWS服务器的实例ID。我用create_instances()命令创建一个ec2服务器,该服务器返回一个列表:

    instance = ec2_resource.create_instances(
        ImageId=image_id,
        MinCount=1,
        MaxCount=max_count,
        InstanceType=instance_type,
        KeyName=key_name,
        SubnetId=subnet_id
     print(instances)

给我这个:[ec2.Instance(id='i-0ee74643266b26fca')]

我正在尝试仅使用实例ID(在引号之间)。我正在尝试像这样剥离它:

instance_id = str(instance).strip('[ec2.Instance(id=\'\')]')
print(f"Instance ID: {instance_id}")

但是我得到的是这个:

Instance ID: -0ee74643266b26f

[在i的开头剥离i-0ee74643266b26fca

我无法在以后的调用中使用结果,因为它缺少i。如何正确执行此操作?

python
2个回答
2
投票

strip对待不是将参数作为要删除的前缀/后缀,而是将其视为包含要删除的各个字符的可迭代对象。完全由参数中的字符组成的任何前缀或后缀不论顺序如何,都会被剥离。

>>> "fofofofofo".strip("of")
""

而不是除去周围的字符,请使用正则表达式extract id。

import re


if (m := re.search("id='(.*)'", s)) is not None:
    instance_id = m.group(1)

或Python 3.8之前的版本,>]

m = re.search("id='(.*)'", s)
if m is not None:
    instance_id = m.group(1)

0
投票

我将使用split而不是strip


0
投票

代替条带可以使用

© www.soinside.com 2019 - 2024. All rights reserved.