Python替换Rubys grep?

ast*_*nic 1 ruby python

abc=123
dabc=123
  abc=456
  dabc=789
    aabd=123
Run Code Online (Sandbox Code Playgroud)

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

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

matches = input.grep(/^\s*abc=.*/).map(&:strip)
Run Code Online (Sandbox Code Playgroud)

我是Python中的一个完全noob,甚至说我是一个新的Python开发人员太多了.

也许有一个更好的"Python方式",甚至没有grepping?

我需要解决问题的平台上提供的Python版本是2.6

当时没有办法使用Ruby

kin*_*all 5

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

  • 为清楚起见,+1 开头。我会使用 `with open("myfile.txt") 作为 myfile`。 (2认同)