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

如何移除列表元素中X前多余数字,统一元素长度?

Solution to Trim Digits Before X to 4 Characters

Hey there! Let's figure out how to process your number list exactly as you want. The goal is to take each string in your list, and for every segment ending with X, keep only the last 4 digits before the X (removing any extra digits that come before those 4).

Step-by-Step Approach

We can use Python's re module (regular expressions) to efficiently find and replace these digit-X patterns. The regex will target any sequence of digits followed by X, and replace it with just the final 4 digits plus X.

Working Code Example

import re

# Your original list
num_list = ["9222111X 9555222X", "9777666X 9555111X", "9333555X 9444222X"]

# Process each item with regex substitution
processed_num_list = [re.sub(r'(\d{4})\d*X', r'\1X', item) for item in num_list]

print(processed_num_list)
# Output: ["9222X 9555X", "9777X 9555X", "9333X 9444X"]

How the Regex Works

Let's break down the pattern r'(\d{4})\d*X':

  • (\d{4}): This captures exactly 4 consecutive digits (the ones we want to keep) into a group.
  • \d*: Matches any number of extra digits (0 or more) that come before the final 4 digits we're keeping.
  • X: Targets the trailing X that marks the end of each segment.

The replacement r'\1X' uses the captured 4-digit group (\1) and appends X to it, effectively trimming off the extra digits.

Edge Case Note

If you might have segments where there are fewer than 4 digits before X (e.g., "123X"), you can adjust the regex to r'(\d{1,4})\d*X'—this will keep all existing digits (1-4) instead of requiring exactly 4. But based on your example, the original pattern should work perfectly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:03:37