3

I work in a Python shell. In order to produce a list of all global names I use dir(), but it generates a very long list, which I would like to filter. I am interested only in the names which begin with 'f' and end with digits. Sometimes I also need only user-defined names, no __*__ names. Is there any grep-like method in a Python shell to filter its output?

1
  • It won't help with the digit suffix requirement, but to easily list names for a prefix, try a shell with completion - e.g. bpython, ipython, dreampie, idle, spyder... Commented Sep 12, 2011 at 16:17

3 Answers 3

2
[name for name in dir() if name.startswith('f') and name[-1].isdigit()]

Example:

>>> f0 = 7
>>> [name for name in dir() if name.startswith('f') and name[-1].isdigit()]
['f0']
Sign up to request clarification or add additional context in comments.

2 Comments

it can be more digits than 1 last only
This code will check if the last character is a digit, but won't exclude filenames with a string of digits at the end of the name
2
>>> import re
>>> [item for item in dir() if re.match(r'f.*\d+$',item)]

or

>>> [item for item in dir() if re.search(r'^f.*\d+$',item)]

Comments

1

[n for n in dir() if re.match("f.*[0-9]$", n)]

I set my PYTHONSTARTUP environment variable to point to ~/.startup.py which contains:

# Ned's startup.py file, loaded into interactive python prompts.

print("(.startup.py)")

import datetime, os, pprint, re, sys, time

print("(imported datetime, os, pprint, re, sys, time)")

def dirx(thing, regex):
    return [ n for n in dir(thing) if re.search(regex, n) ]

pp = pprint.pprint

Now I always have a few handy modules imported, and I have shortcuts available for things I often do in the shell.

3 Comments

The OP wants the names to end with digits, and re.match() matches only at the beginning, so you need a $ in your regex. As it stands you are accepting food22xyz. Also consider .*? for efficiency. #pedantic
True, true. Fixed the regex. Since this is entered by hand for ad-hoc queries, the .*? would actually slow down the query, since the time to type (and fix the typos in) the extra character will vastly outweigh the extra time the simpler regex would use. #takethat
The way you have written re.match("f.*[0-9]$") in your list comprehension does not work, does it? You either need a compiled regex pattern object or use the two arg form of re.match(pattern,string)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.