gpt4 book ai didi

Python 替代 Ruby 的 grep?

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:35 25 4
gpt4 key购买 nike

abc=123
dabc=123
abc=456
dabc=789
aabd=123

我需要从上面的文件中找到以 abc= 开头的行(空格无关紧要)

在 ruby​​ 中我会把它放在一个数组中然后做

matches = input.grep(/^\s*abc=.*/).map(&:strip)

我对 Python 完全是菜鸟,说我是 Python 新手也过分了。

也许有更好的“Python 方式”来做到这一点,甚至不需要 grepping?

我在需要解决问题的平台上可用的Python版本是2.6

当时没有办法使用Ruby

最佳答案

with open("myfile.txt") as myfile:
matches = [line.rstrip() for line in myfile if line.lstrip().startswith("abc=")]

关于Python 替代 Ruby 的 grep?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12451027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com