【问题标题】:Replace a word in a String by indexing without "string replace function" -python通过不使用“字符串替换功能”的索引来替换字符串中的单词-python
【发布时间】:2018-10-28 02:15:02
【问题描述】:

有没有一种方法可以在不使用“字符串替换函数”的情况下替换字符串中的单词,例如 string.replace(string,word,replacement)。

[out] = forecast('This snowy weather is so cold.','cold','awesome')
out => 'This snowy weather is so awesome.

这里的cold这个词被替换为awesome。

这是我尝试在 python 中完成的 MATLAB 作业。在 MATLAB 中执行此操作时,我们不允许使用 strrep()。

在 MATLAB 中,我可以使用 strfind 查找索引并从那里开始工作。但是,我注意到列表和字符串之间存在很大差异。字符串在 python 中是不可变的,可能需要导入一些模块才能将其更改为不同的数据类型,这样我就可以像我想要的那样使用它,而无需使用字符串替换函数。

【问题讨论】:

    标签: python string indexing replace


    【解决方案1】:

    只是为了好玩:)

    st = 'This snowy weather is so cold .'.split()
    given_word = 'awesome'
    for i, word in enumerate(st):
        if word == 'cold':
            st.pop(i)                                                                                                                                                                 
            st[i - 1] = given_word
            break # break if we found first word
    
    print(' '.join(st))
    

    【讨论】:

    • Shoot 我要补充一点,我想避免在这个分配中使用迭代,因为我们此时还没有学习迭代。
    【解决方案2】:

    这是另一个可能更接近您使用 MATLAB 描述的解决方案的答案:

    st = 'This snow weather is so cold.'
    given_word = 'awesome'
    word_to_replace = 'cold'
    n = len(word_to_replace)
    
    index_of_word_to_replace = st.find(word_to_replace)
    
    print st[:index_of_word_to_replace]+given_word+st[index_of_word_to_replace+n:]
    

    【讨论】:

    • 谢谢。我应该能够想出这个解决方案,因为这与 MATLAB 解决方案非常相似。是否有提示找到这些程序的解决方案。我似乎在这方面挣扎了很多,并且想了很多。
    【解决方案3】:

    你可以将你的字符串转换成一个列表对象,找到你要替换的词的索引,然后替换这个词。

    sentence = "This snowy weather is so cold"
    
    # Split the sentence into a list of the words
    words = sentence.split(" ")
    
    # Get the index of the word you want to replace
    word_to_replace_index = words.index("cold")
    
    # Replace the target word with the new word based on the index
    words[word_to_replace_index] = "awesome"
    
    # Generate a new sentence
    new_sentence = ' '.join(words)
    

    【讨论】:

      【解决方案4】:

      使用正则表达式和列表推导。

      import re
      def strReplace(sentence, toReplace, toReplaceWith):
          return " ".join([re.sub(toReplace, toReplaceWith, i) if re.search(toReplace, i) else i for i in sentence.split()])
      
      print(strReplace('This snowy weather is so cold.', 'cold', 'awesome'))
      

      输出:

      This snowy weather is so awesome.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-01
        • 2016-12-15
        • 1970-01-01
        • 2012-08-31
        • 1970-01-01
        • 2015-07-03
        相关资源
        最近更新 更多