[英]How to delete the very last character from every string in a list of strings
我在列表中有字符串 '80010'、'80030'、'80050',如
test = ['80010','80030','80050']
如何刪除最后一個字符(在這種情況下,每個字符串的最后一個數字為 0),以便我可以得到另一個僅包含每個字符串前四位數字/字符的列表? 所以最終得到類似的東西
newtest = ['8001', '8003', '8005']
我對 Python 非常陌生,但我嘗試過使用 if-else 語句、附加、使用索引 [:-1] 等,但除非我最終刪除所有其他零,否則似乎沒有任何效果。 非常感謝!
test = ["80010","80030","80050"]
newtest = [x[:-1] for x in test]
新測試將包含結果["8001","8003","8005"]
。
[x[:-1] for x in test]
通過循環遍歷test
每個項目並將修改后的版本放入newtest
創建一個新列表(使用列表理解)。 x[:-1]
表示取字符串值 x 中的所有內容,但不包括最后一個元素。
你並沒有那么遠。 使用切片符號 [:-1] 是正確的方法。 只需將它與列表理解結合起來:
>>> test = ['80010','80030','80050']
>>> [x[:-1] for x in test]
['8001', '8003', '8005']
somestring[:-1]
為您提供從位置 0(包含)的字符到最后一個字符(不包含)的所有內容。
只是為了展示一個與理解略有不同的解決方案,鑒於其他答案已經解釋了切片,我只介紹了該方法。
帶地圖功能。
test = ['80010','80030','80050']
print map(lambda x: x[:-1],test)
# ['8001', '8003', '8005']
有關此解決方案的更多信息,請閱讀我在另一個類似問題中所做的簡要說明。
在python中@Matthew解決方案是完美的。 但是,如果您確實是一般編碼的初學者,我必須推薦這個,肯定不那么優雅,但這是許多其他情況下的唯一方法:
#variables declaration
test = ['80010','80030','80050']
lenght = len(test) # for reading and writing sakes, len(A): lenght of A
newtest = [None] * lenght # newtest = [none, none, none], go look up empty array creation
strLen = 0 # temporary storage
#adding in newtest every element of test but spliced
for i in range(0, lenght): # for loop
str = test[i] # get n th element of test
strLen = len (str) # for reading sake, the lenght of string that will be spliced
newtest[i] = str[0:strLen - 1] # n th element of newtest is the spliced n th element from test
#show the results
print (newtest) # ['8001','8003','8005']
ps:這個腳本雖然不是最好的,但可以在 python 中運行! 祝任何程序員新人好運。
我有一個類似的問題,這里是解決方案。
List<String> timeInDays = new ArrayList<>();
timeInDays.add(2d);
timeInDays.add(3d);
timeInDays.add(4d);
我需要刪除每個字符串中的最后一個字母以便比較它們。 以下解決方案對我有用。
List<String> trimmedList = new ArrayList<>;
for(int i=0;i<timeInDays.size();i++)
{
String trimmedString = timeInDays.get(i).substring(0,name.length()-1);
trimmedList=add(trimmedString );
}
System.out.println("List after trimming every string is "+trimmedList);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.