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

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

listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', '000alphanumeric']

删除 末尾的 0 后对应的输出是:

listOfNum = ['000231512-n','1209123100000-n','alphanumeric', '000alphanumeric']

之后删除前导 0 后的理想输出为:

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)
277554 次浏览

那基本的呢

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]

你试过 带():

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


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

删除前导 + 后跟’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 ]

你可以简单地使用一个 bool:

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

对于这种情况,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安装的第三方库。

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


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时可能更方便