【问题标题】:how to check if the is any char (a - b) in string [duplicate]如何检查字符串中是否有任何字符(a - b)[重复]
【发布时间】:2017-03-24 14:59:17
【问题描述】:

我正在尝试检查某些字符串是否包含 a - z 中的任何字符。 我看到我可以在in 中使用,但这似乎不是像这样传递整个字符串的最舒服的方式:

if a in string
if b in string
if c in string

你能帮我找出正在做的函数/算法吗?它也适用于数字吗?

【问题讨论】:

标签: python


【解决方案1】:

尝试使用正则表达式

import re
If re.search(r"[a-z]", s):
    ...

【讨论】:

    【解决方案2】:

    将您的输入字符串转换为列表,然后像这样发布过程:

    list(set([x for x in a if x in b]))
    

    脚本:

    STRING = ";alkd779-n;l--xswdlfkj"
    TEST = "abcde"
    
    string = list(STRING)
    test = list(TEST)
    matches =  list(set([x for x in string if x in test]))
    contains_match = True if len(matches)>0 else False
    
    print 'string         : %s' % string
    print 'test           : %s' % test
    print 'matches        : %s' % matches 
    print 'contains match : %s' % contains_match
    
    >>>
    string         : [';', 'a', 'l', 'k', 'd', '7', '7', '9', '-', 'n', ';', 'l', '-', '-', 'x', 's', 'w', 'd', 'l', 'f', 'k', 'j']
    test           : ['a', 'b', 'c', 'd', 'e']
    matches        : ['a', 'd']
    contains match : True
    

    【讨论】:

    • 我想在没有 for 循环的情况下尝试它(我猜这个想法谢谢)。那么为什么要在这个算法中使用 'set' 函数呢?
    • 设置删除重复项
    • 如果测试列表中存在项目,则将项目从字符串列表逐项移动到匹配列表
    猜你喜欢
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2015-09-14
    • 1970-01-01
    • 2013-02-26
    • 2012-04-21
    • 2019-11-22
    相关资源
    最近更新 更多