Pavan Sangha
Pavan Sangha

Reputation: 251

Python printing two things on one line

I'm working through the edx python course. I've done everything correctly in the last assignment. However, I'm struggling with this print issue.

I have a function displayHand(hand) which essentially takes a dictionary with keys being letters and values be the number of occurrences of the letters. The function then prints a string with each key appearing the same number of times as its value. So for example if

hand={a:3, b:4, c:1}
displayHand(hand)=a a a b b b b c

Now in the program for any given hand it wants me to display it using the displayHand function with the text "current hand: "

Again, if hand={a:3, b:4, c:1} the program should display

current hand: a a a b b b b c

How do I do this with a print statement? I've tried print("current hand"+str(displayHand(hand)), but this first evaluates the function and then just prints None. I can't put print("Current Hand: ") and displayHand(hand) directly underneath, because then they print on different lines. I need to get them to print on the same line.

Upvotes: 1

Views: 5816

Answers (4)

Spherical Cowboy
Spherical Cowboy

Reputation: 566

Python 3:

def displayHand(dct):
    for key, val in sorted(dct.items()):  # sorted if key order should be abc
        print((key + " ") * val, end="")


hand = {"a": 3, "b": 4, "c": 1}

print("current hand: ", end="")
displayHand(hand)

Notice the end="" which appends whatever is inside "". The default setting is end="\n". In this case, we will just use an empty string. See here and here.

Output:

current hand: a a a b b b b c 

Upvotes: 4

Cleb
Cleb

Reputation: 25997

You could do the following:

def displayHand(hand):
    print('{} {}'.format('current hand:', ' '.join([' '.join([li] * ni) for li, ni in sorted(hand.items())])))

That creates a string first which is then printed.

Then

displayHand(hand)

prints the desired output:

current hand: a a a b b b b c

Upvotes: 0

Symonen
Symonen

Reputation: 737

That should work for you :

print("current hand: ", end="")
displayHand(hand)

In print() function default end is new line. In the code above you just change it to whatever you want.

Upvotes: 1

Ali Camilletti
Ali Camilletti

Reputation: 135

You can use print twice, you just have to add a comma after the first print ex: print("a"), print("b").

Upvotes: 0

Related Questions