📌  相关文章
📜  Python|用单个替换多个出现的字符

📅  最后修改于: 2022-05-13 01:55:31.855000             🧑  作者: Mango

Python|用单个替换多个出现的字符

给定一个字符串和一个字符,编写一个Python程序,用一个字符。

例子:

Input : Geeksforgeeks, ch = 'e'
Output : Geksforgeks

Input : Wiiiin, ch = 'i'
Output : Win

方法#1:朴素的方法
这种方法是一种蛮力方法,我们采用另一个列表“new_str”。使用 for 循环检查给定字符是否重复。如果重复多次,则将字符单次附加到列表中。其他字符(不是给定字符)只是简单地附加到列表中而没有任何更改。

# Python program to replace multiple 
# occurrences of a character by a single character
  
def replace(s, ch):
    new_str = []
    l = len(s)
      
    for i in range(len(s)):
        if (s[i] == ch and i != (l-1) and
           i != 0 and s[i + 1] != ch and s[i-1] != ch):
            new_str.append(s[i])
              
        elif s[i] == ch:
            if ((i != (l-1) and s[i + 1] == ch) and
               (i != 0 and s[i-1] != ch)):
                new_str.append(s[i])
                  
        else:
            new_str.append(s[i])
          
    return ("".join(i for i in new_str))
  
  
# Driver code 
s = 'Geeksforgeeks'
char = 'e'
print(replace(s, char))
输出:
Geksforgeks


方法 #2:使用Python正则表达式

import re
  
# Function to replace multiple occurrences  
# of a character by a single character
def replace(string, char):
    pattern = char + '{2,}'
    string = re.sub(pattern, char, string)
    return string
  
# Driver code 
string = 'Geeksforgeeks'
char = 'e'
print(replace(string, char))
输出:
Geksforgeks