簡體   English   中英

在同一行上打印函數輸出和字符串?

[英]Print function output and strings on same line?

我正在編寫一個程序,該程序應該在由星星組成的盒子中打印一個單詞,如下所示:

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

但是,我得到以下輸出:

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

我知道我一直得到“ None”的輸出,因為我不能在同一行上print string和函數輸出。 我該怎么辦?

我的代碼如下:

    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)

您的問題是由於您正在調用在print語句中打印某些內容的函數而引起的。 我的建議是讓spaces_str()star_str() 返回字符串而不是打印它。

更好的是,完全消除這些功能。 " " * 40完全可讀且慣用; 將其包裝在函數中只是要鍵入更多字符而不會增加可讀性。

在方法末尾給出return語句而不是print,現在下面的打印將產生正確的結果

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

我會使用@kindall並return字符串,而不是僅僅打印它,但還要指出的是,可以使用尾隨逗號來抑制print語句的顯式換行符:

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

test_print()
# one two three 

然后您可以不應該寫:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM