如何删除前导和绳子拖着为零? 蟒蛇(How to remove leading and trai

2019-06-18 17:34发布

我有几个字母数字串这样的

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']

现在,我已经做了以下的方法,请提出一个更好的方式,如果有:

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)

Answer 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]


Answer 2:

拆下通往+尾随“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 ]


Answer 3:

你尝试用条() :

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']
print [item.strip('0') for item in listOfNum]

>>> ['231512-n', '1209123100000-n', 'alphanumeric', 'alphanumeric']


Answer 4:

你可以简单地用一个布尔值,这样做:

if int(number) == float(number):

   number = int(number)

else:

   number = float(number)


Answer 5:

str.strip是造成这种情况的最好方法,但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"满足谓词其他元素之间的第 这个工具不仅限于字符串。

另请参见文档了解更多的例子

  • more_itertools.strip :剥离两端
  • more_itertools.lstrip :剥去左端
  • more_itertools.rstrip :剥去右端

more_itertools是一个第三方库安装的经> pip install more_itertools



文章来源: How to remove leading and trailing zeros in a string? Python