[英]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.