dislikesAppleCores
dislikesAppleCores

Reputation: 320

Print formatting a string and function call in python

I've got a function, displayHand() which looks like this:

def displayHand(hand):
    """
    Displays the letters currently in the hand.

    For example:
    >>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
    Should print out something like:
       a x x l l l e
    The order of the letters is unimportant.

    hand: dictionary (string -> int)
    """
    for letter in hand.keys():
        for j in range(hand[letter]):
             print letter,              # print all on the same line
    print                              # print an empty line

It was provided for me (from the 600x class). As described, it takes a dict of string->ints and prints out the "hand".

What I'm having troubles with is getting this to show up properly. When I try

print('Current Hand: ', displayHand(hand))

This is what I get:

a d d m o q y 
('Current Hand: ', None)

Since this was provided by the instructor, I'm sure there's a reason the code was written this way and that there's something I'm not getting.

What I'd like to get is output like this:

Current Hand: a d d m o q y

I'm absolutely brand new to this stuff so I don't even know what questions to ask.

My assessment: As far as I can piece together, displayHand() doesn't return anything and that's what's screwing it all up. But how do I catch the print output of this function and present it the way I want? I was thinking I should try to catch it in a string and have that returned, but assuming

the instructor was trying to demonstrate something, how would I do it without changing the displayHand() method?

If my assessment is off, what's going on?

Edit: This function was given to me by the class, and I'll have to use it as such. I understand changing it to return a str would be much easier, but how could I accomplish the correct output without doing that?

Further Edit: I'm dealing with an autograder that demands the output exactly as I've written. Sorry to be so fussy, I appreciate the answers and would use them if it wasn't for this.

Final Edit: Thanks for the clarification -- I'm going to use your idea and make a helper function inside this function that does what I need it to do!

FINAL final Edit: I figured it out! All I had to do was,

print('Current Hand:'),
displayHand(hand)

For real final edit:

Hah! you got it too! thank you so much for the help, I appreciate it!

Upvotes: 0

Views: 8769

Answers (4)

Elisiano Petrini
Elisiano Petrini

Reputation: 602

If you really can't modify that function then you might want to redirect the standard output to a string before calling the function and setting it back to normal afterwards.

This post explains how to do it: Can I redirect the stdout in python into some sort of string buffer?

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1125068

Your function already prints, it does not return anything.

Don't try to 'catch' the printed output, simply change the function to return the hand, formatted to a string:

def displayHand(hand):
    letters = []
    for letter, count in hand.iteritems():
        letters.extend([letter] * count)
    return ' '.join(letters)

which gives:

>>> hand = {'a': 1, 'q': 1, 'd': 2, 'y': 1, 'm': 1, 'o': 1}
>>> displayHand(hand)
'a q d d y m o'
>>> print 'Current Hand:', displayHand(hand)
Current Hand: a q d d y m o

If you are not supposed to change the displayHand() function, then use the same trick using in the function and do not print a newline by adding a comma to the end of the print statement:

print 'Current Hand:',
displayHand(hand)

Upvotes: 2

wRAR
wRAR

Reputation: 25569

First, your displayHand function doesn't return anything so when you try to print its result you get None. You probably need to remove those print statements from the function and return the string instead.

Second, you try to use print as a function which is possible obly in python 3 while you seem to be using python 2. If that's the case you need to remove parentheses around the print statement arguments.

Upvotes: 0

Pavel Anossov
Pavel Anossov

Reputation: 62948

You can do this if you must use the provided function and must not try to fix it:

print('Current Hand: ', end='')
displayHand(hand)

I'm confused, do you use python 2 or 3?

In python 2:

print 'Current Hand" ',
displayHand(hand)

Upvotes: 2

Related Questions