Python - 在扩展其他字符串的同时保持字符串完整
Python - Keeping string intact while extending other string
我的代码将文件逐行拆分为字符串并将它们扩展为列表。
我注意到对于 仅扩展一个 字符串的情况,结果将拆分该字符串并将其逐个字母扩展到空列表。如果我删除 [-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
接受一个可迭代对象。
因此,当您将字符串 (ghi
) 传递给它时,它会像列表一样使用它,并使用该字符串中的字符扩展列表。
您可能想将该字符串放入列表或使用 list.append
。
我的代码将文件逐行拆分为字符串并将它们扩展为列表。
我注意到对于 仅扩展一个 字符串的情况,结果将拆分该字符串并将其逐个字母扩展到空列表。如果我删除 [-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
接受一个可迭代对象。
因此,当您将字符串 (ghi
) 传递给它时,它会像列表一样使用它,并使用该字符串中的字符扩展列表。
您可能想将该字符串放入列表或使用 list.append
。