![](/img/trans.png)
[英]Log parsing in Python: Alert if more than N errors in a given period?
[英]Remove more than 1 period in String - Python
我有一個簡單的字符串。 在這個字符串中,我可以有任何數字。 有時這個數字有超過 1 個句點。 我的目標是刪除超過 1 個句點,所以如果我以一個為例,它應該看起來像這樣 = 20.00011。 我怎樣才能做到這一點?
import re
a = "20.00.0.11"
a_replaced = re.sub(r'\.+', ".", a)
print(a_replaced)
嘗試這個 -
a = "20.00.0.11"
t = a.split('.') #breaks the item into token
t[0]+'.'+''.join(t[1:]) #join them back with a single .
'20.00011'
如果您有所有可能,您可能有多個。或單個或沒有。那么您可以使用以下 function -
a = "20.00.0.11"
b = "20.000"
c = "20000"
def fix_dots(a):
t = a.split('.')
if len(t)>1:
return t[0]+'.'+''.join(t[1:])
else:
return t[0]
print(fix_dots(a))
#Output - '20.00011'
print(fix_dots(b))
#Output - '20.000'
print(fix_dots(c))
#Output - '20000'
解決此問題的列表理解方法是使用查找第一個點的位置,然后使用 OR 條件來保留該點並忽略其他點。
a = "20.00.0.11"
def fix_dot2(a):
return ''.join([i[1] for i in enumerate(a) if i[0]==a.find('.') or i[1]!='.'])
print(fix_dot2(a))
'20.00011'
"".join("20.00.0.11".replace(".","!",1).split(".")).replace("!",".")
或者:
string = "20.00.0.11"
dot = string.find(".")
"".join([x for (i, x) in enumerate(string) if (x != ".") | (i==dot)])
另一種解決方案是用“。”拆分,並確保在列表的第二個索引處添加一個。
a = "20.00.0.11"
lst = a.split('.')
lst.insert(1, '.')
a_replaced = ''.join(lst)
print(a_replaced)
>>> "20.00011"
使用這個版本會給你一個更壓縮的一行代碼:
a = "20.00.0.11"
a_replaced = ''.join(a.split('.').insert(1, '.'))
此解決方案假定輸入的第一個期間是您要保留的期間。
此外,如果輸入中沒有句點,則會在字符串末尾添加一個句點。 如果你不想要這個,你需要添加一個如果檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.