gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:11:13 29 4
gpt4 key购买 nike

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

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)

最佳答案

基本款呢

your_string.strip("0")

删除尾随和前导零?如果您只对删除尾随零感兴趣,请改用 .rstrip (而 .lstrip 仅用于前导零)。

更多信息见 doc.

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

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]

关于python - 如何删除字符串中的前导零和尾随零? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13142347/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com