我的代碼將文件逐行分解爲字符串並將它們擴展爲列表。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
我還沒有理解你想要實現什麼 – magicleon
你能提供一個完整的例子嗎?你的'abc','dfe','ghi'應該是字符串文字嗎?如果您可以提供完全複製您的問題的準確代碼以及預期輸出,那將更容易爲您提供幫助。 –
@AlexAlifimoff:https://meta.stackoverflow.com/a/256331/2988730 –