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


110

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

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)

Answers:


238

那基本的

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]

2
在特殊情况下,此答案是否有任何巧妙的调整s = '0'
查尔斯(Charles)

7
@查尔斯:是的!我只是遇到了同样的问题,您可以执行以下操作s.strip("0") or "0":如果您的字符串变成空字符串,则将其评估为False或并将替换为所需的字符串"0"
tarulen

@Pierre GM谢谢。它确实有帮助,而且非常简单。投票
Vishav Gupta

18

删除前导+尾随的“ 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 ]

感谢您的回答。真的有帮助。我已经投票赞成
Vishav Gupta,

7

您可以简单地通过bool做到这一点:

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

   number = int(number)

else:

   number = float(number)

2
不能与alphanumeric0000OP 一起使用。
卡尔·里希特

4

您是否尝试了strip()

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

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

1

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"将满足谓词的其他元素中的前导和尾随s 剥离。此工具不仅限于字符串。

另请参阅docs,以获取更多的示例

more_itertools是可通过安装的第三方库> pip install more_itertools


1

假设列表中还有其他数据类型(不仅是字符串),请尝试此操作。这将从字符串中删除尾随和前导零,并使其他数据类型保持不变。这也处理特殊情况s ='0'

例如

a = ['001', '200', 'akdl00', 200, 100, '0']

b = [(lambda x: x.strip('0') if isinstance(x,str) and len(x) != 1 else x)(x) for x in a]

b
>>>['1', '2', 'akdl', 200, 100, '0']
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.