python - 当“$”出现时,我将如何打印所有实例?
问题描述
我有这个字符串,我基本上是在“$”出现后尝试获取数字。例如,我想要这样的输出:
>>> 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])
有没有更简单的方法可以做到这一点,或者我只是忘记了什么?
解决方案
正则表达式耶:
import re
matches = re.findall(r'\$(\d+\.\d+|\d+)', file)
查找所有整数和浮点数,确保尾随 '.' 句号不会被错误地捕获。
推荐阅读
- python - 如何操纵单例?
- postgresql - 获取上个月的第一个日期
- xamarin - 如何为 Xamarin Native iOS 和 Android 应用程序的新页面添加 ViewModel
- r - 如何使用 ifelse 函数根据数据框中另一列的条件更改列中某些行的值?
- python - 挣扎着使用scrapy登录网站
- c - 在另一个结构中初始化和使用结构成员
- dll - MTOUCH:错误 MT0009:加载程序集时出错:grpc_csharp_ext.x64.dll (MT0009)
- python - 从列中选取值
- sql - 如何在第二个条件内编写具有 2 个条件和 OR 语句的 CASE?
- r - 恢复基础库