![](/img/trans.png)
[英]How to remove leading zeros from the calculator expression in a string? python
[英]How to remove leading and trailing zeros in a string? 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-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)
刪除前導 + 尾隨 '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 ]
你可以簡單地用一個布爾值來做到這一點:
if int(number) == float(number):
number = int(number)
else:
number = float(number)
您是否嘗試過strip() :
listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']
print [item.strip('0') for item in listOfNum]
>>> ['231512-n', '1209123100000-n', 'alphanumeric', 'alphanumeric']
假設您的列表中有其他數據類型(而不僅僅是字符串),試試這個。 這會從字符串中刪除尾隨零和前導零,並保持其他數據類型不變。 這也處理特殊情況 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']
str.strip
是這種情況的最佳方法,但more_itertools.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.strip
兩端more_itertools.lstrip
: more_itertools.lstrip
左端more_itertools.rstrip
: more_itertools.rstrip
右端 more_itertools
是一個第三方庫,可通過> pip install more_itertools
。
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
時可能更方便
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.