首页 > 解决方案 > 当“$”出现时,我将如何打印所有实例?

问题描述

我有这个字符串,我基本上是在“$”出现后尝试获取数字。例如,我想要这样的输出:

>>> 100, 654, 123, 111.654

变量和字符串:

file = """| $100 on the first line
          | $654 on the second line
          | $123 on the third line
          | $111.654 on the fourth line"""

到现在为止,我有一些我认为可以帮助我区分数字的代码。但我不明白为什么它只分隔第四行。它只会打印出来111.654

txt = io.StringIO(file).getvalue()
idx = txt.rfind('$')

print(txt[idx+1:].split()[0])

有没有更简单的方法可以做到这一点,或者我只是忘记了什么?

标签: python

解决方案


正则表达式耶:

import re

matches = re.findall(r'\$(\d+\.\d+|\d+)', file)

查找所有整数和浮点数,确保尾随 '.' 句号不会被错误地捕获。


推荐阅读