148

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

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

7 回答 7

315

基本的怎么办

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]
于 2012-10-30T15:30:35.647 回答
19

删除前导 + 尾随 '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 ]
于 2012-10-30T15:33:28.383 回答
9

你可以简单地用一个 bool 来做到这一点:

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

   number = int(number)

else:

   number = float(number)
于 2016-03-05T12:58:56.740 回答
4

您是否尝试过strip()

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

>>> ['231512-n', '1209123100000-n', 'alphanumeric', 'alphanumeric']
于 2012-10-30T15:33:11.117 回答
2

假设您的列表中有其他数据类型(而不仅仅是字符串),请尝试此操作。这会从字符串中删除尾随和前导零,并保持其他数据类型不变。这也处理特殊情况 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']

于 2019-10-24T20:03:40.003 回答
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。此工具不限于字符串。

另请参阅文档以获取更多示例

more_itertools是一个第三方库,可通过> pip install more_itertools.

于 2017-08-23T17:59:22.627 回答
0

pandas还提出一个方便的方法:

listOfNum = pd.Series(['000231512-n','1209123100000-n00000','alphanumeric0000', '000alphanumeric'])

listOfNum.str.strip("0")
listOfNum.str.ltrip("0")
listOfNum.str.rtrip("0")

第一个会给出,例如:

0           231512-n
1    1209123100000-n
2       alphanumeric
3       alphanumeric
dtype: object

这在使用时可能更方便DataFrames

于 2021-10-14T16:18:45.533 回答