\ n行制动器的运算符在字符串列表中不起作用[重复] https://www.nytimes.com/2018/12/12/technology/amazon-new-york-hq2-data。 html

问题描述 投票:-2回答:2

我的问题是我有一篇文章,我想打印每行(标题和作者说明除外),并在其前面加上相应的行号。我通过列举每一行并将其附加到列表中来做到这一点。现在,我希望每行分开(因此在每个'。'之后添加行制动器\ n),但这似乎不起作用,因为输出仍会打印\ n而不是所需的换行符。

来源:https://www.nytimes.com/2018/12/12/technology/amazon-new-york-hq2-data.html

article = """High-Tech Degrees and the Price of an Avocado: The Data New York Gave to Amazon\n\nThe city and state sent loads of data to Amazon during its search for a new headquarters, offering a peek into the valuable information the company collected during the process.\n\nKaren Weise\n\nBy Karen Weise\n\n\tDec. 12, 2018\n\n[Updated Feb. 14: Amazon said it was canceling plans to build a corporate campus in New York City, after the deal had run into fierce opposition from local lawmakers who criticized providing subsidies to one of the world’s most valuable companies.]\n\nAn avocado at Whole Foods costs 1.25. \nColumbia University handed out 724 graduate degrees in computer science over the past three years. \nAnd 10 potential land parcels in Long Island City are zoned M1-4, for light manufacturing.\n\nNew York provided all of these data points, and thousands more, to Amazon as part of its successful bid to woo the tech giant to town.\n\nOn Monday, New York City posted online the 253-page proposal it submitted, along with New York State, to Amazon in March. \nThe city quickly took the file down, saying it should have checked with its partners before posting it, because the document included proprietary information. \nBut The New York Times downloaded the document before it was taken off the public website.\n\nThe proposal shows the types of data, some rarely available publicly, that the company amassed from cities across the country as part of its search for a second headquarters.
"""

def make_nice(article):
    '''Makes a list of all line in the given article, drops the third and six line, arranges the meta-data about author and data in a sensible way
    and add number of lines to their lines '''

    article = list(filter(None, article.replace("\t", "-").split("\n")))
    article.pop(2)
    article.pop(4)
    new_article=[]

    for index, article in enumerate(article, start=-3):   # default is zero
        if index >= 1:
            new_article.append(str(f"{index}| {article} \n"))
        elif index == -1:
            new_article.append(article)
        else:
            new_article.append(f"{article} \n")
    return new_article

print(make_nice(article))
print(type(make_nice(article)))
python string list line-breaks
2个回答
0
投票

如果您不需要列表,为什么要首先创建列表。您可以按如下所示修改函数,并直接将其作为字符串获取。您可以继续使用f字符串。我使用.format()是因为我使用的是Python 3.5,并且它不支持f字符串。

def make_nice(article):

    article = list(filter(None, article.replace("\t", "-").split("\n")))
    article.pop(2)
    article.pop(4)
    new_article = ''

    for index, article in enumerate(article, start=-3):   # default is zero
        if index >= 1:
            new_article += (str('{}| {} \n'.format(index, article)))
        elif index == -1:
            new_article += (article)
        else:
            new_article += ("{} \n".format(article))
    return new_article

0
投票

您的函数make_nice()返回一个字符串列表,然后直接单击print()。您可能会得到如下输出:

['foo ', 'bar ', '3 | baz\n'...]

这是Python中列表的字符串表示形式(您可以通过调用new_article.__str__()-请参阅__str__()文档进行检查;以列表的字符串表示形式。

为了将new_article列表中的字符串打印为一个带换行符的字符串,您必须将它们连接为一个字符串,然后打印该字符串:

print(''.join(make_nice(article)))

请参见str.join()的文档。

© www.soinside.com 2019 - 2024. All rights reserved.