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?
-
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...Beni Cherniavsky-Paskin– Beni Cherniavsky-Paskin2011-09-12 16:17:54 +00:00Commented Sep 12, 2011 at 16:17
Add a comment
|
3 Answers
[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']
2 Comments
psihodelia
it can be more digits than 1 last only
joel goldstick
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
[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
Ray Toal
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. #pedanticNed Batchelder
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
dawg
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)