2012-10-30 121 views
59

我有幾個字母數字串這樣的如何刪除字符串中的前導和尾隨零? Python的

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) 

回答

123

有關基本什麼

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] 
+1

對於's ='0''這個特殊情況,這個答案是否有任何巧妙的調整? – Charlie

3

你嘗試用strip()

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

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

刪除前導+尾隨'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

你可以簡單地這樣做有一個布爾值:

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

    number = int(number) 

else: 

    number = float(number) 
+0

根據OP的要求,不能使用'alphanumeric0000'。 –

0

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"。這個工具不限於字符串。 See docs獲取更多示例。

相關問題