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

如何在python中向字符串添加新行

如何在python中向字符串添加新行,python,string,list,printing,Python,String,List,Printing,我有这个密码 def fullview(): rows = 3 elems_in_row = 4 List = ['-'] * rows for i in range(rows): List[i] = ['-'] * elems_in_row for i in List: elements = ''.join(i) fullview = str(rows)+ ':' + elements

我有这个密码

def fullview():    
    rows = 3
    elems_in_row = 4
    List = ['-'] * rows
    for i in range(rows):
        List[i] = ['-'] * elems_in_row   
    for i in List:
        elements = ''.join(i)
        fullview = str(rows)+ ':' + elements
        rows -= 1
   return fullview
当我向fullview添加一行时,它会删除添加到其中的前一行。 我期望的结果是:

fullview = """
3:----
2:----
1:----
"""

我不知道如何将新行正确地添加到字符串中,因为+=不起作用。

这可以通过一个构造完成,而不是多个步骤:

result = '\n'.join(['{}:{}'.format(i, '-' * elements_in_row)
                    for i in range(1, rows + 1)][::-1])
原始代码不起作用的一个原因是行更新
fullview
没有考虑以前的状态:

fullview = str(rows)+ ':' + elements
只需使用“\n”

def fullview():
    rows = 3
    elems_in_row = 4
    fullview_str = ''
    for i in range(rows, 0, -1):
        fullview_str += "{}:{}\n".format(i, '-' * elems_in_row)
    return fullview_str
示例输出:

3:----
2:----
1:----

顺便说一句,用函数名表示函数中的变量不是一个好主意。这不会影响代码中的任何内容,但如果函数是递归的,则会有影响。但不这样做的主要原因是它会使代码读起来很混乱。