Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否在同一行上打印函数输出和字符串?_Python_String_Printing - Fatal编程技术网

Python 是否在同一行上打印函数输出和字符串?

Python 是否在同一行上打印函数输出和字符串?,python,string,printing,Python,String,Printing,我正在写一个程序,应该在一个由星星组成的盒子里打印一个单词,如下所示: ************ * * * danielle * * * ************ 但是,我得到了以下输出: ************ * None * * danielle * * None * ************ 我知道我一直得到“无”的输出,因为我不能在同一行上打印字符串和函数输出。我怎么能这样做 我的代码如下:

我正在写一个程序,应该在一个由星星组成的盒子里打印一个单词,如下所示:

************
*          *
* danielle *
*          *
************
但是,我得到了以下输出:

************
*           
None *
* danielle *
*           
None *
************
我知道我一直得到“无”的输出,因为我不能在同一行上打印
字符串
和函数输出。我怎么能这样做

我的代码如下:

    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\u str()
star\u str()
返回字符串,而不是打印它


更好的是,完全消除这些功能
“*40
可读性和惯用性极佳;将其包装到函数中只需输入更多字符,而不会增加可读性。

在方法末尾给出一个返回语句,而不是打印,现在您下面的打印将产生正确的结果

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

我会使用@kindall和
返回
字符串,而不仅仅是打印它,但我也会指出,可以通过使用尾随逗号来抑制
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

+1.打印而不是返回字符串的函数几乎总是一个坏主意。