Python:如何提取指定标识符前的7个字符?
Got it, let's sort this out for you. Your current code grabs everything before the "Type of Occurrence" identifier, but we just need the last 7 characters of that prefix. Here are two straightforward ways to fix this:
Option 1: Improve Your Existing Split Approach
You can keep using split() to get the full prefix, then slice the last 7 characters from it. This builds on the code you already have and keeps things simple:
A = "12/07/2019 11 : 00Type of Occurrence" # Get all content before the identifier full_prefix = A.split('Type of Occurrence', 1)[0] # Extract the last 7 characters of the prefix target_substring = full_prefix[-7:] # Apply your existing formatting rules print(target_substring.replace('.', '').upper())
This will output exactly 11 : 00 as you need. For edge cases where the prefix might be shorter than 7 characters, add a quick check to avoid errors:
full_prefix = A.split('Type of Occurrence', 1)[0] if len(full_prefix) >= 7: target_substring = full_prefix[-7:] else: target_substring = full_prefix # Or handle this scenario based on your needs
Option 2: Use Regular Expressions for Precise Matching
If you prefer a one-step solution, regex lets you directly capture the 7 characters right before your identifier:
import re A = "12/07/2019 11 : 00Type of Occurrence" # Capture exactly 7 characters immediately preceding the identifier match = re.search(r'(.{7})Type of Occurrence', A) if match: target_substring = match.group(1).replace('.', '').upper() print(target_substring)
The regex pattern (.{7}) captures any 7 characters, and Type of Occurrence anchors this capture right before your target identifier. This is ideal if you want to skip handling the full prefix entirely.
内容的提问来源于stack exchange,提问作者Mohannad

