简体   繁体   中英

How can I simplify this expression?

I want to check whether some strings and their lowercase variants can be found inside another,but my code seems pointlessly complex.

this works, but I want to know whether a cleaner variant exists:

if ("aaa" in string or "Aaa" in string or "bbb" in string or "Bbb" in string) and C not in list:
   function()

you can try:

if any(s in string for s in ('aaa', 'Aaa', 'bbb', 'Bbb')) and C not in list:
   function()

Using a regex:

import re
if re.search('|'.join(['aaa', 'Aaa', 'bbb', 'Bbb']), string) and C not in mylist:
    function()

Use a regex range, which affords one to easy modify possible matches in the future; you can also add the re.IGNORECASE to make the match case insensitive:

    import re
    l = [ "Aaa", "bbb", "C" ]
    for ele in l:
         if (re.match(r'[ab]+', ele, re.IGNORECASE)):
             function()

Note: I'm trying to simply the need to check your string and list, but I don't know if that feasible.

Here is an another method using list comprehension. Its long though but it works:

if True in [1 for _ in ["aaa","Aaa","Bbb","bbb"] if _ in string] and C not in list:
    function()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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