如何在python中从列表中搜索字符串

时间:2016-12-12 11:54:54

标签: python

我有python代码:

bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8'))
try:
    response = s3.get_object(Bucket=bucket, Key=key)
    contents = response['Body'].read()
    print(contents)

它会显示如下结果:

D_REGION="east"

A_NAME="diet"

V_ID="44"

K_PASS="N/A"

TRIAL_PRODUCTION="TRIAL"

我想通过检查值是 TRIAL 还是值 PROD 来验证这一点 然后打印整个列表否则会失败。 我们如何使用python从列表中搜索字符串?

2 个答案:

答案 0 :(得分:2)

>>> contents = '''D_REGION="east"
... 
... A_NAME="diet"
... 
... V_ID="44"
... 
... K_PASS="N/A"
... 
... TRIAL_PRODUCTION="TRIAL"'''
>>> import re
>>> re.search(r'TRIAL_PRODUCTION="(TRIAL|PROD)"', contents).group(1)
'TRIAL'

答案 1 :(得分:0)

>>> contents = """D_REGION="east"
... 
... A_NAME="diet"
... 
... V_ID="44"
... 
... K_PASS="N/A"
... 
... TRIAL_PRODUCTION="TRIAL"
... """
>>> # couldn't be much simpler:
>>> 'TRIAL_PRODUCTION="TRIAL"' in contents or 'TRIAL_PRODUCTION="PROD"' in contents
True
>>> # a bit more elegant
>>> any(target in contents for target in ('TRIAL_PRODUCTION="TRIAL"', 'TRIAL_PRODUCTION="PROD"'))
True

现在尝试使用Python之前学习Python(至少是最基本的东西)呢?