pearbear
pearbear

Reputation: 1055

Print function output and strings on same line?

I am writing a program that is supposed to print a word in a box made of stars like this:

************
*          *
* danielle *
*          *
************

However, I am getting the following output:

************
*           
None *
* danielle *
*           
None *
************

I know I keep getting an output of "None" because I can't print a string and a function output on the same line. How could I do this?

My code is as follows:

    def star_str(length):
    stars = '*'*length
    print stars

def spaces_str(length):
    spaces = " "*length
    print spaces

def frame_word(input_word):
    length = len(input_word)
    top_bottom_stars = length + 4
    spaces_middle = length + 2

    star_str(top_bottom_stars)
    print '*', spaces_str(spaces_middle), '*'
    print '*', input_word, '*'
    print '*', spaces_str(spaces_middle), '*'

    star_str(top_bottom_stars)

print "Please enter a word:",
input_word = raw_input()
frame_word(input_word)

Upvotes: 1

Views: 3587

Answers (3)

Jon Clements
Jon Clements

Reputation: 142256

I'd go with @kindall and return the string rather than just print it, but would also point out that it's possible to suppress an explicit newline for a print statement by using a trailing comma:

def test_print():
    print 'one',
    print 'two',
    print 'three'

test_print()
# one two three 

Then you could but shouldn't write:

print '*', # suppresses newline
spaces_str() # this prints using something as above
print '*' # asterisk and newline

Upvotes: -1

Vivek S
Vivek S

Reputation: 5550

give a return statement at the end of the method instead of print , now your print below will produce proper result

def spaces_str(length):
    spaces = " "*length
    return spaces
print '*', spaces_str(spaces_middle), '*'

Upvotes: 0

kindall
kindall

Reputation: 184455

Your problem is caused by the fact that you're calling a function that prints something within a print statement. My suggestion would be to have spaces_str() and star_str() return the string rather than printing it.

Better yet, eliminate those functions entirely. " " * 40 is perfectly readable and idiomatic; wrapping it in a function is just more characters to type without an increase in readability.

Upvotes: 4

Related Questions