You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中忽略特殊字符仅匹配文本,检查字符串是否在列表中

Solution to Match Plain Text Against List Items with Special Characters

Got it, let's break down why your original code isn't working first: you're checking if plain target strings exist directly in list_count—but those list items have extra characters like {, }, and \n, so exact matches can't happen. We need to strip out those special characters from the list items first before checking for matches.

Step-by-Step Fix

First, we'll make a helper function to clean unwanted characters and normalize messy whitespace. Then we'll process all items in your list, and finally check each target string against the cleaned content.

Here's the working code:

import re

# Your target strings
string1 = 'hi'
string2 = 'I'
string3 = 'am new to this'
strings_to_check = [string1, string2, string3]

# The list containing special characters
list_count = ["{hi}","\n I","am \n new {to} this\n\n"]

def clean_special_chars(text):
    # Remove {, }, and newline characters first
    cleaned = re.sub(r'[\{\}\n]', '', text)
    # Fix whitespace: replace multiple spaces with one, then trim edges
    cleaned = re.sub(r'\s+', ' ', cleaned).strip()
    return cleaned

# Pre-clean all list items (using a set for faster lookup performance)
cleaned_list_items = {clean_special_chars(item) for item in list_count}

# Check each target string
for target in strings_to_check:
    if target in cleaned_list_items:
        print(f"'{target}' -> yes")
    else:
        print(f"'{target}' -> no")

How This Works

  1. Cleaning Function: clean_special_chars() uses regex to:
    • Remove {, }, and \n from each list item
    • Normalize messy whitespace (like leading spaces left from removed newlines, or multiple consecutive spaces)
  2. Pre-Clean the List: We process all list items once and store them in a set—sets are faster for membership checks than lists, which helps if your list grows large.
  3. Check Targets: Loop through each target string and verify if it exists in the cleaned set of list items.

Customization Tip

If you need to ignore more special characters (like [, ], or !), just add them to the regex character set: for example, change re.sub(r'[\{\}\n]', '', text) to re.sub(r'[\{\}\n\[\]!]', '', text).

内容的提问来源于stack exchange,提问作者Perl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:19:17