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

Python技术求助:提取字符串中A、B后整数并分别求和

问题描述
  • 字符串由字母和数字组合而成
  • 每个字母后必定跟有一个整数,但整数的位数不固定
  • 字母"A"的位置有规律:将所有字母替换为分隔符(如逗号)后,"A"始终处于3的倍数位置,已实现提取"A"后的整数并求和
  • 字母"B"的位置无规律

目标:

  1. 分别提取字符串中所有"A"和"B"后面的整数
  2. 分别对提取到的整数求和

已尝试的方法:
处理"A"的代码:

s = 'A4B2d2A14d3B11A20B10d10'
s_replace = s.replace('A', ',').replace('B', ',').replace('d', ',')[1:]
test_n = [int(n) for n in s_replace.split(',') if n.isdigit()]
test_Asum = sum(test_n[i] for i in range(len(test_n)) if i % 3 == 0)

print(test_Asum)
# 38

找到"B"索引的代码:

test_B_index = [Bindx for Bindx, char in enumerate(s) if char == "B"]
print(test_B_index)
# [2, 11, 17]

目前无法提取"B"索引位置之后的任意位数整数。


解决方案

方法一:正则表达式(推荐)

直接匹配A\d+和B\d+的模式,精准提取字母后的数字:

import re

s = 'A4B2d2A14d3B11A20B10d10'

# 提取A后数字并求和
a_numbers = [int(m.group(1)) for m in re.finditer(r'A(\d+)', s)]
a_sum = sum(a_numbers)

# 提取B后数字并求和
b_numbers = [int(m.group(1)) for m in re.finditer(r'B(\d+)', s)]
b_sum = sum(b_numbers)

print(f"A后面的整数和:{a_sum}")  # 输出38
print(f"B后面的整数和:{b_sum}")  # 输出23

说明:r'A(\d+)'匹配字母A后的连续数字,(\d+)作为捕获组提取数字部分,转成整数后直接求和即可。该方法无需依赖A的位置规律,同时能高效处理无规律的B。

方法二:手动遍历字符串

如果不想用正则,可通过遍历字符串收集目标字母后的数字:

s = 'A4B2d2A14d3B11A20B10d10'

def extract_numbers_after_char(s, target_char):
    numbers = []
    str_len = len(s)
    idx = 0
    while idx < str_len:
        if s[idx] == target_char:
            # 从下一个位置开始收集连续数字
            num_str = ''
            idx += 1
            while idx < str_len and s[idx].isdigit():
                num_str += s[idx]
                idx += 1
            if num_str:
                numbers.append(int(num_str))
        else:
            idx += 1
    return numbers

a_numbers = extract_numbers_after_char(s, 'A')
b_numbers = extract_numbers_after_char(s, 'B')

print(f"A后面的整数和:{sum(a_numbers)}")  # 38
print(f"B后面的整数和:{sum(b_numbers)}")  # 23

说明:遍历字符串时,遇到目标字母(A/B)就从下一位开始收集连续数字字符,直到遇到非数字为止,最后将收集到的字符串转为整数并求和。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 19:33:15