【问题标题】:Replacing a word in a string in python 3在python 3中替换字符串中的单词
【发布时间】:2019-10-24 21:34:15
【问题描述】:

我正在尝试编写一个函数,将句子中的一个单词(这是两个单独的字符串)替换为“-”。它可以工作,但我可以弄清楚如何使用 len 来制作它,以便它为单词中的字符数打印正确数量的破折号。

我一直在使用 str.replace() 但我不知道如何在 len(word) 中正确工作到函数中,以便它打印正确数量的破折号。

sentance=("what is tomorrow's date?")
word="what"

def replaceWord():
        print (sentance.replace(word,"----",))

replaceWord()

【问题讨论】:

  • 一个技巧:你可以将一个字符串乘以一个数字:'-' * 5 == "-----"。因此,将 5 替换为 len(word) 即可获得正确数量的破折号。
  • sentance.replace(word,"-" * len(word))
  • 我看到有两个人回答了这个问题,但在没有任何有效的 cmets 的情况下被否决了.... 鱼腥味...根本不喜欢它....
  • @Abdurrahim 可能是因为发布代码而没有解释(我没有投票,但我可以看到已删除的答案)。如果你怀疑犯规,你可以在这个问题上提出一个 mod 标志并解释你的怀疑。
  • 那么那些人应该开始写 cmets 来说明他们不同意的地方。如您所知,stackoverflow 允许编辑,因此他们可能有机会改进他们的答案。但这种行为首先会阻止人们回答

标签: python


【解决方案1】:

试试:

def replaceWord(s, w):
    word_len = len(w)
    dashes = '-' * word_len
    print(s.replace(w,dashes));

s = "what is tomorrow's date?"
w = "what"
replaceWord(s, w)

在python中,可以将一个字符串与一个数字相乘以获得重复的字符串。

【讨论】:

    【解决方案2】:

    只需将破折号字符串乘以这样的单词的 len

    dash = '-'
    wl = len(word)
    string_to_replace = dash * wl
    

    【讨论】:

      【解决方案3】:

      你已经得到了答案。但是,在这里我给你另一种方法来实现你的目标。这样,您就可以随意选择自己的分隔符(例如'-'、'*'、'/'等)。

      def replaceWord(sep, word, sentence):
          """
              :param sep: That is the separator.
              :param word: That is the work to replace.
              :param sentence: That is the sentence.
          """
          len_word = len(word)
          replacer = sep * len_word
          print(sentence.replace(word, replacer))
      
      sentence = "what is tomorrow's date?"
      word = "what"
      sep = "-"  # you can change it
      replaceWord(sep, word, sentence)
      

      输出:

      ---- is tomorrow's date?
      

      【讨论】:

        猜你喜欢
        • 2014-04-01
        • 2012-09-14
        • 2015-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多