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

Python如何从含正负数字的字符串中拆分字符串与数字?

解决含正负数字的连字符分割问题

问题描述

给定如下字符串模式:

A = 'this is an_example-0--1.5-60-NA'

需要提取出以下内容:

string[0] = 'this is an_example'
string[1] = -1.5
string[2] = 60
string[3] = 'NA'

其中string[1]和string[2]可以是正数或负数,直接使用string.split('-')会把负号误判为分隔符,无法实现需求。

解决方案:使用正则表达式

利用正则表达式可以精准匹配目标内容,避免误分割负号。以下是实现代码:

import re

A = 'this is an_example-0--1.5-60-NA'
# 正则表达式匹配四个目标部分
pattern = r'^(.*?)-\d+--?([+-]?\d+\.?\d*)-([+-]?\d+\.?\d*)-(\w+)'
match_result = re.match(pattern, A)

if match_result:
    # 提取并转换对应内容
    part0 = match_result.group(1)
    part1 = float(match_result.group(2))
    part2 = int(match_result.group(3))
    part3 = match_result.group(4)
    
    # 输出结果
    print(f"string[0] = '{part0}'")
    print(f"string[1] = {part1}")
    print(f"string[2] = {part2}")
    print(f"string[3] = '{part3}'")

正则表达式说明

  • ^:匹配字符串起始位置
  • (.*?):非贪婪捕获开头的文本内容(即this is an_example),直到遇到后续的-数字--结构
  • -\d+--:匹配固定格式的-数字--部分(如示例中的-0--)
  • ([+-]?\d+\.?\d*):捕获可选正负号的整数或浮点数,兼容正数、负数、整数、小数的情况
  • (\w+):捕获最后一个部分(如示例中的NA)

运行上述代码后,即可得到预期的提取结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 06:02:48