我有一个简单的字符串。在这个字符串中,我可以有任何数字。有时这个数字有 1 个以上的句点。我的目标是删除超过 1 个句点,所以如果我以 a 为例,它应该看起来像这样 = 20.00011。我怎样才能做到这一点?
import re
a = "20.00.0.11"
a_replaced = re.sub(r'\.+', ".", a)
print(a_replaced)
一只斗牛犬
浏览 112回答 3
3回答
慕村225694
尝试这个 -a = "20.00.0.11"t = a.split('.') #breaks the item into tokent[0]+'.'+''.join(t[1:]) #join them back with a single .'20.00011'如果万一你有所有的可能性,你可能有多个 .'s 或一个或没有 .'s 那么你可以使用以下功能 -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'