我的代码是将一个文件逐行拆分成字符串,并将它们扩展到一个列表中。你知道吗
我注意到,如果只扩展了一个字符串,则结果将拆分该字符串,并将其逐字母扩展到空列表。如果删除[-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
list.extend
接受iterable。你知道吗因此,当您向它传递一个字符串(
ghi
)时,它就像一个列表一样使用它,用该字符串中的字符扩展列表。你知道吗您可能希望将该字符串放入列表或使用
list.append
。你知道吗相关问题 更多 >
编程相关推荐