Python中忽略特殊字符仅匹配文本,检查字符串是否在列表中
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
- Cleaning Function:
clean_special_chars()uses regex to:- Remove
{,}, and\nfrom each list item - Normalize messy whitespace (like leading spaces left from removed newlines, or multiple consecutive spaces)
- Remove
- 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.
- 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

