[英]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.