我有几个字母数字串这样的
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)
有关基本什么
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]
拆下通往+尾随“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 ]
你尝试用条() :
listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']
print [item.strip('0') for item in listOfNum]
>>> ['231512-n', '1209123100000-n', 'alphanumeric', 'alphanumeric']
你可以简单地用一个布尔值,这样做:
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.strip
:剥离两端 -
more_itertools.lstrip
:剥去左端 -
more_itertools.rstrip
:剥去右端
more_itertools
是一个第三方库安装的经> pip install more_itertools
。