Slade
Slade

Reputation: 183

How to print out the command used to execute code without executing it in Python

I'm intermediate level, so this may be an easy question, but I have no idea how to word it correctly, so sorry in advance.

I am trying to show what command leads to what output, and print all of that out. So an example: numpy.arange(2) prints out an array and I want to use a print statement to say:
numpy.arange(2) 'prints' array
where array would be the actual array

So my code is:

phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo = phoneNumRegex.search('My number is 415-555-4242.')
for i in range(1,3):
    y = str(mo.group(i))
    x = mo.group(i)
    print y + "outputs" + x

And so my goal is to say that 'mo.group(1) outputs' and whatever the output of that is, then 'mo.group(2) outputs' and whatever that output is. The actual outputs don't matter, but I want the mo.group(i) to take the value i, but not execute it. Whatever code I tried doesn't work for what I am attempting. Sorry if that's confusing. Thanks a lot!

Upvotes: 1

Views: 655

Answers (2)

22degrees
22degrees

Reputation: 645

When you use str, you are saying "make a string out of the object returned by mo.group(i)". What you need is this

y = "mo.group({:})".format(i)

This says "make a string literal object; then use that object's format method to replace {:} with the value of the object i, whatever type that is"

You can take it one step further by doing something like this:

print "mo.group({:}) output is : {:}".format(i,x)

Which prints the values of i and x and a little text describing it all in one line. "".format() is the prefered way to do this in python > 2.6, and there's lots it can do. Check the documentation to see what it's capable of.

Upvotes: 1

flankstaek
flankstaek

Reputation: 11

I believe you want to be saying x = type(mo.group(i)) and print that, that will give you the type that mo.group(i) returns such as str, int, etc.

Upvotes: 0

Related Questions