最佳答案
我有几个这样的字母数字字符串
listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', '000alphanumeric']
删除 末尾的 0 后对应的输出是:
listOfNum = ['000231512-n','1209123100000-n','alphanumeric', '000alphanumeric']
之后删除前导 0 后的理想输出为:
listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']
删除前导零和末尾的零之后的期望输出如下:
listOfNum = ['231512-n','1209123100000-n', 'alphanumeric', '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)