如何去除字符串中的某些连续重复字符?

3 投票
2 回答
2441 浏览
提问于 2025-04-17 19:58

我想定义一个函数,这个函数接收一个字符串和这个字符串中的一个字母,然后输出一个新字符串,这个新字符串中只保留这个字母出现一次。例如:

my_function("happy kitten","p")
'hapy kitten' 

或者

my_function("happykitten","t") 
'happykiten'

我试过

def my_function(string, lett):
newString = ""
for char in string: #all characters
    for s in string: #character I'm testing
        if s == len(s) > 1: 
            newString+=lett # if there are multiple occurrences of s, replace with lett since its a single char anyway
        else:
            newString+=char #if not a duplicate, add next char to newString
    return newString #("happy kitten","p") returns 'ppppppppppp'

还有

def my_function(string, lett):
newString = ""
for char in string: #all characters
    for s in string: #character I'm testing
        if s == s+1: 
            newString+=lett # if there are multiple occurrences of s, replace with lett since its a single char anyway
        else:
            newString+=char #if not a duplicate, add next char to newString
    return newString #TypeError: cannot concatenate 'str' and 'int' objects

我的函数哪里出错了?请不要使用导入或内置函数。

2 个回答

2

逐个遍历字符的方式效率不高,而且很可能是错误的做法。这听起来就像是大学新生的作业。在实际情况中,你应该考虑使用正则表达式,而这个问题似乎提供了一个很好的解决方案。

你的问题在于你假设 s+1 指向迭代器中的下一个值,但这并不是一个正确的假设。你需要做的是记录下你看到的内容,然后在下一次迭代时相应地处理。

为了练习,我们仍然可以解决这个问题:

def strip_duplicate_letters(input, letter):
  output = ''
  last = False

  for c in input:
    if c == letter:
      if last:
        continue
      else:
        last = True
    else:
      last = False
    output += c

  return output

这是一个非常基础的概念,你需要仔细思考一下,确保自己理解了。然后忘掉这个例子,自己再做一遍。

另一种方法是给字母编号,这样就能得到索引号:

for i, c in enumerate(input):
  if i > 0 and c == letter and input[i-1] == letter:
    continue
  output += c

如果觉得使用 enumerate 太复杂,你可以用一个整数作为计数器,并让它递增。

i = 0
for c in input:
  ....
  i += 1
  ...
4

如果你对导入的库或者内置函数改变了主意,你随时可以这样做:

from itertools import groupby

def my_function(s, c):
    return ''.join(c if a==c else ''.join(b) for a,b in groupby(s))

>>> from itertools import groupby
>>> def my_function(s, c):
...     return ''.join(c if a==c else ''.join(b) for a,b in groupby(s))
... 
>>> my_function("happy kitten","p")
'hapy kitten'
>>> my_function("happykitten","t")
'happykiten'

撰写回答