Python-忽略特殊字符并仅匹配文本

时间:2018-05-17 10:08:15

标签: python string

我正在尝试检查列表中是否存在字符串:

我的字符串没有任何特殊字符,如{,},\ n,\ n \ n

list_count="{hi}","\n I","am \n new {to} this\n\n"

其中我的列表条目包含如下字符串:

for i in strings:
    if i in list_count:
        print('yes')

我想知道如何只考虑"文本部分"我是如何检查字符串匹配的?列表

注意:我有n个要检查的字符串

我试过下面的代码,似乎无法实现我的目的

的字符串=字符串1,字符串,STRING3

代码:

if 'hi' in list_count:

我希望输出对于以下检查是肯定的:

{{1}}

只需检查文字部分而不包括' {' '}'

1 个答案:

答案 0 :(得分:1)

您需要通过删除特殊字符,空格等来转换list_count

list_count="{hi}","\n I","am \n new {to} this\n\n"
string1='hi'
string2='I'
string3='am new to this'
strings=string1,string2,string3

ignored = ['{','}','\n']

final_list = []
for item in list_count:
    for k in ignored:
        # remove special characters
        item = item.replace(k,"")
    # remove extra spaces
    item = " ".join(item.split())
    final_list.append(item)

for i in strings:
    if i in final_list:
        print('yes')
相关问题