Skip to main content
 首页 » 编程设计

python之如何在python中替换字符串中的..

2025年05月04日20java哥

我正在尝试将这个字符串替换成这个

import re  
 
s = "haha..hehe.hoho" 
s = re.sub('[..+]+',' ', s) 

我的输出是 haha hehe hoho

期望的输出

haha hehe.hoho 

我做错了什么?

请您参考如下方法:

在像正则表达式这样的网站上测试:http://regexpal.com/ 更容易获得输出并检查正则表达式是否正确。

您应该将正则表达式更改为:'\.\.'如果你只想删除双点。 如果你想在至少有 2 个点时删除,你可以使用 '\.{2,}'。

你放在 [] 中的每个字符都会根据你的表达式进行检查 点字符在正则表达式中有特殊含义,为避免这种含义,您应该在其前面加上转义字符:\

您可以在此处阅读有关正则表达式元字符的更多信息:https://www.hscripts.com/tutorials/regular-expression/metacharacter-list.php

[a-z] A range of characters. Matches any character in the specified range.

. Matches any single character except "n".

\ Specifies the next character as either a special character, a literal, a back reference, or an octal escape.

您的新代码:

import re  
 
s = "haha..hehe.hoho" 
#pattern = '\.\.' #If you want to remove when there's 2 dots 
pattern = '\.{2,}' #If you want to remove when there's at least 2 dots 
s = re.sub(pattern, ' ', s)