我有几个这样的字母数字字符串
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-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)
发布于 2012-10-30 23:30:36
基本的怎么样?
your_string.strip("0")
去掉尾随零和前导零?如果您只对删除尾随零感兴趣,请改用.rstrip
(只对前导零使用.lstrip
)。
有关更多信息,请访问doc.
您可以使用一些列表理解来获得所需的序列,如下所示:
trailing_removed = [s.rstrip("0") for s in listOfNum]
leading_removed = [s.lstrip("0") for s in listOfNum]
both_removed = [s.strip("0") for s in listOfNum]
发布于 2012-10-30 23:33:28
删除前导+尾随'0':
list = [i.strip('0') for i in listOfNum ]
删除前导'0':
list = [ i.lstrip('0') for i in listOfNum ]
删除尾随的'0':
list = [ i.rstrip('0') for i in listOfNum ]
发布于 2016-03-05 20:58:57
您可以使用bool简单地完成此操作:
if int(number) == float(number):
number = int(number)
else:
number = float(number)
https://stackoverflow.com/questions/13142347
复制相似问题