Python在扩展其他字符串时保持字符串完整

2024-05-15 17:48:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码是将一个文件逐行拆分成字符串,并将它们扩展到一个列表中。你知道吗

我注意到,如果只扩展了一个字符串,则结果将拆分该字符串,并将其逐字母扩展到空列表。如果删除[-1],字符串将保持完整,但其他字符串也将被扩展。你知道吗

在将字符串扩展到空列表时,如何防止该字符串被拆分?你知道吗

searchstring = "abc dfe ghi"     #resembles a searchline from a file
text = searchstring.split()          #note: same thing happens if i add [-1] here
list1.extend(text[-1])           #I only want the last element of the string

所以输出是:

print list1
[abc, dfe, ghi]

或者

print list1
[g, h, i]

但我需要这样

print list1
[ghi]             #one entry for each line in the file

Tags: 文件the字符串代码text列表字母file
1条回答
网友
1楼 · 发布于 2024-05-15 17:48:05

list.extend接受iterable。你知道吗

因此,当您向它传递一个字符串(ghi)时,它就像一个列表一样使用它,用该字符串中的字符扩展列表。你知道吗

您可能希望将该字符串放入列表或使用list.append。你知道吗

相关问题 更多 >