首页 > 解决方案 > Python:仅从字符串中提取 00-00-00 格式的数字

问题描述

我有一个这样的字符串:Test Step 01-08-04 U upper 100 m/s

目前我使用:

self.current_xtp_test_case = re.findall("\d+", test_case.attrib["name"])
self.current_xtp_test_case = ''.join(map(str,self.current_xtp_test_case[-1:]))
self.current_xtp_test_case = self.current_xtp_test_case.lstrip("0")

上面应该得到 00-00-00 模式中的最后一个数字,最终应该是4因为我需要删除0. 但是现在有了我正在处理的数据,有时可能会有一个数字,而不是00-00-00上面的例子,我在最后的字符串中有 100,这弄乱了我当前代码的逻辑。

如何更改我的代码,以便我只能选择模式 01-03-04 中的最后一个数字 - 我只想选择04零件。希望这是有道理的?

标签: python

解决方案


你可以这样做:

s = ['Test Step 00-00-00 U upper 0 m/s',
     'Test Step 00-00-09 U upper 100 m/s',
     'Test Step 01-08-04 U upper 150 m/s']
[re.findall('[0-9]{2,}\-[0-9]{2,}\-([0-9]{2,})',x)[0] for x in s]

输出:

['00', '09', '04']

希望有所帮助;)


推荐阅读