如何在一个字符串中去除开头和结尾的零?Python
如何在一个字符串中去除开头和结尾的零?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-n', 'alphanumeric', 'alphanumeric']
目前我是这样做的,请提供更好的方法:
listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', \ '000alphanumeric'] trailingremoved = [] leadingremoved = [] bothremoved = [] # 去除尾部零 for i in listOfNum: while i[-1] == "0": i = i[:-1] trailingremoved.append(i) # 去除前导零 for i in listOfNum: while i[0] == "0": i = i[1:] leadingremoved.append(i) # 去除前导和尾部零 for i in listOfNum: while i[0] == "0": i = i[1:] while i[-1] == "0": i = i[:-1] bothremoved.append(i)