繁体   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