如何在Python中将String与List结合使用?

时间:2018-04-19 21:23:50

标签: python string python-3.x python-2.7

我是Python新手,我想知道如何将String与List的所有元素组合,然后将Output保存在.txt文件中。但窗口只是因为代码错误而立即打开和关闭。这是我的代码:

List = [1, 2, 3, 4, 5]

String = input("Please enter a name: ")
Output = String + List
print(Output)

f= open("Text.txt","w+")
f.write(Output + "\n")
f.close()

我期待看到这样的结果:

Please enter a name: Username
Username1 Username2 Username3 Username4 Username5

在像这样的文本文件中:

Username1
Username2
Username3
Username4
Username5

我该怎么做?如果问题不明确,请告诉我。我的第一语言不是英语,所以我很难解释。谢谢你的时间:))

2 个答案:

答案 0 :(得分:4)

我估计你可以使用列表理解:

List = [1, 2, 3, 4, 5]

String = input("Please enter a name: ")

Output = [String + str(x) for x in List]

print(Output)

输出:

['Username1', 'Username2', 'Username3', 'Username4', 'Username5']

答案 1 :(得分:1)

按照Jacob G.的条目,您的代码应如下所示:

> dput(dbGet_TRUE_EVENTS_DATA)
structure(list(LONGITUDE = c(-39.5, -39.5, -38.5, -38.5, -39.5, 
-38.5, -39.5, -38.5, -39.5, -38.5, -39.5), LATITUDE = c(80.5, 
81.5, 80.5, 81.5, 79.5, 79.5, 79.5, 79.5, 79.5, 79.5, 79.5), 
    DATE_START = structure(c(1215298800, 1215298800, 1215298800, 
    1215298800, 1215298800, 1215298800, 1215298800, 1215298800, 
    1215298800, 1215298800, 1215298800), class = c("POSIXct", 
    "POSIXt")), DATE_END = structure(c(1215644400, 1215644400, 
    1215644400, 1215644400, 1215644400, 1215644400, 1215644400, 
    1215644400, 1215644400, 1215644400, 1215644400), class = c("POSIXct", 
    "POSIXt")), FLAG = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), EQNUM = c(1, 
    1, 2, 2, 3, 3, 4, 4, 5, 6, 7)), .Names = c("LONGITUDE", "LATITUDE", 
"DATE_START", "DATE_END", "FLAG", "EQNUM"), row.names = c(NA, 
-11L), class = "data.frame")

> dput(TRUE_EVENTS_split_up)
structure(list(Fold1 = c(3, 4, 6), Fold2 = c(5, 7), Fold3 = c(1, 
2)), .Names = c("Fold1", "Fold2", "Fold3"))