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

Python:如何提取指定标识符前的7个字符?

Solution to Extract 7 Characters Before a Specific Identifier

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:32:09