【问题标题】:Replacing a single character when there are duplicates有重复字符时替换单个字符
【发布时间】:2015-09-24 04:54:32
【问题描述】:

我要做的只是一个循环遍历单词或短语的程序,如下所示:

word: "dog"
d
do
dog
do
d

这是我写的:

word = 'factory'
temp_word = ''
temp_word2 = ''

# Builds up 'factory' letter-by-letter into temp_word
for i in word:
    temp_word += i
    print(temp_word)

# Takes letters off 1 by 1
for i in reversed(word):
    temp_word2 = temp_word.replace(i, "")
    temp_word = temp_word2
    print(temp_word2)

输出正是我想要的:

f
fa
fac
fact
facto
factor
factory
factor
facto
fact
fac
fa
f

但是,如果有一个重复的字母,它会同时删除两个,像这样:

h
he
hel
hell
hello
hell
he
he
h

我怎样才能让它只删除一个字母,而不删除两个?想不出解决办法

【问题讨论】:

    标签: python loops python-3.x for-loop


    【解决方案1】:

    这里有一个解决方案,它不是最好的。根据您要对此执行的操作,我可以提供更具体的解决方案

    word = 'hello'
    temp_word = ''
    temp_word2 = ''
    
    for k in word:
        temp_word += k
        print temp_word
    while temp_word:
        temp_word = temp_word[:-1]
        print temp_word 
    

    编辑

    我更喜欢这个版本

    word = 'hello'
    for k in list(range(1,len(word)+1)) + list(range(len(word)-1,1,-1)):
        print word[:k]
    

    【讨论】:

      【解决方案2】:

      您是否使用临时变量,还是只允许使用字符串切片?

      for i in range(1,len(word)+1):
          print(word[:i])
      
      for i in range(len(word)-1,0,-1): #the third argument of range is step, and -1 causes range to step backwards
          print(word[:i])
      

      【讨论】:

      • 切片创建一个新字符串
      • ...derp。我以某种方式设法将其解读为 python2.7 问题。修复。
      • @PadraicCunningham 嗯,是的,但是这样你就不必处理临时变量或类似的东西了。
      【解决方案3】:

      您可以将计数传递为1 来替换以仅替换一次。

      temp_word2 = temp_word.replace(i, "",1)
      

      你也可以把最后一个字母切掉:

      for i in reversed(word):
          temp_word2 = temp_word[:-1]
      

      【讨论】:

      • 在这两个选项中,您认为哪个是首选方法?
      • 他们都创建了一个新字符串,所以可能差别不大
      猜你喜欢
      • 1970-01-01
      • 2020-08-14
      • 2012-02-27
      • 2020-09-14
      • 2015-03-17
      • 1970-01-01
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      相关资源
      最近更新 更多