删除字符串中的某些连续重复项?

时间:2013-03-22 12:39:08

标签: python

我想定义一个函数,该函数在该字符串中包含一个字符串和一个字母,并输出一个新字符串,该字符串的出现次数为一次。例如

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 个答案:

答案 0 :(得分: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'

答案 1 :(得分:2)

迭代字符是低效的,很可能是错误的事情。听起来很像是一个新生课程的家庭作业。在现实生活中,你应该研究正则表达式,this question似乎提供了一个优雅的答案。

你的问题是你假设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
  ...
相关问题