如何删除string中的前导和尾随零? python
我有几个这样的字母数字string
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']
现在我已经这样做了,请build议一个更好的方法,如果有:
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)
怎么样一个基本的
your_string.strip("0")
去除尾随和前导零? 如果您只想删除尾随零,请使用.rstrip
代替(而.lstrip
仅适用于.lstrip
零)。
[更多信息在文档中 ]
你可以用一些列表理解来获得你想要的序列:
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]
删除前导+尾随“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 ]
你试过带() :
listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric'] print [item.strip('0') for item in listOfNum] >>> ['231512-n', '1209123100000-n', 'alphanumeric', 'alphanumeric']
你可以简单地用一个bool来做到这一点:
if int(number) == float(number): number = int(number) else: number = float(number)
strip
是这种情况的最佳方法,但more_itertools.strip
是一个通用的解决scheme,从一个迭代中more_itertools.strip
前导和尾随元素:
import more_itertools as mit iterables = ["231512-n\n"," 12091231000-n00000","alphanum0000", "00alphanum"] pred = lambda x: x in {"0", "\n", " "} list("".join(mit.strip(i, pred)) for i in iterables) # ['231512-n', '12091231000-n', 'alphanum', 'alphanum']
请注意,在这里,我们除去了满足谓词的其他元素中的前导和尾随"0"
。 这个工具不限于string。 有关更多示例, 请参阅文档 。