Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.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_Return - Fatal编程技术网

Python 返回多行格式化,结尾没有额外的空行

Python 返回多行格式化,结尾没有额外的空行,python,string,return,Python,String,Return,我试图从一个格式良好的函数返回几行单独的文本。我现在的做法是在末尾添加一行我不想要的额外内容。如何更好地格式化此文件 def myfunction(): mystring = '' for letter in 'cat': mystring += letter + '\n' return mystring 现在的输出是: c a t <this is a blank line at the end> c A. T 我怎样才能去掉那个空行?

我试图从一个格式良好的函数返回几行单独的文本。我现在的做法是在末尾添加一行我不想要的额外内容。如何更好地格式化此文件

def myfunction():
    mystring = ''
    for letter in 'cat':
        mystring += letter + '\n'
    return mystring
现在的输出是:

c
a
t
<this is a blank line at the end>
c
A.
T
我怎样才能去掉那个空行?

正如您所指出的,应该使用而不是字符串加法
join
还负责后面的换行符:

def myfunction():
    return '\n'.join('cat')

请注意,字符串添加通常是一个坏主意,因为它涉及大量的重新分配,并且可能比
str.join

慢得多。建议非常简单,您确实不必添加属性。。。