我有幾個字母數字串這樣的如何刪除字符串中的前導和尾隨零? Python的
listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', '000alphanumeric']
所需的輸出去除尾隨零是:
listOfNum = ['000231512-n','1209123100000-n','alphanumeric', '000alphanumeric']
爲領先尾隨零所需的輸出將是:
listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']
慾望把去除前沿和後零是:
listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']
現在我已經做了以下的方法,請提出一個更好的方式,如果有:
listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', \
'000alphanumeric']
trailingremoved = []
leadingremoved = []
bothremoved = []
# Remove trailing
for i in listOfNum:
while i[-1] == "0":
i = i[:-1]
trailingremoved.append(i)
# Remove leading
for i in listOfNum:
while i[0] == "0":
i = i[1:]
leadingremoved.append(i)
# Remove both
for i in listOfNum:
while i[0] == "0":
i = i[1:]
while i[-1] == "0":
i = i[:-1]
bothremoved.append(i)
對於's ='0''這個特殊情況,這個答案是否有任何巧妙的調整? – Charlie