一尘不染

如何删除字符串中的前导零和尾随零?蟒蛇

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 = []

# 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)

阅读 150

收藏
2020-12-20

共1个答案

一尘不染

那基本的

your_string.strip("0")

删除尾随和前导零?如果您只想删除尾随零,请.rstrip改用(.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]
2020-12-20