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

时间:2012-10-30 15:29:21

标签: python string trailing chomp leading-zero

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

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)

6 个答案:

答案 0 :(得分:172)

基本

怎么样?
your_string.strip("0")

删除尾随和前导零?如果您只想删除尾随零,请使用.rstrip代替(.lstrip仅代替前导零)。

[{3}}中的更多信息。]

你可以使用一些列表理解来获得你想要的序列:

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]

答案 1 :(得分:11)

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

答案 2 :(得分:3)

您是否尝试使用strip()

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

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

答案 3 :(得分:3)

您只需使用bool执行此操作:

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

   number = int(number)

else:

   number = float(number)

答案 4 :(得分: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"以及满足谓词的其他元素。此工具不限于字符串。

有关

的更多示例,另请参阅文档

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

答案 5 :(得分: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']