【问题标题】:Removing part of a string between indices删除索引之间的字符串的一部分
【发布时间】:2020-06-27 19:57:31
【问题描述】:

我要写一个函数,当给定一个字符串时,找到第一次出现的 子字符串“不”和“坏”。如果 'bad' 跟在 'not' 之后,它会将整个 'not'...'bad' 子串替换为 'good'。 例如:“这顿晚餐还不错!”产量:这顿饭不错! 我试过了:

def not_bad(s):
    sub1='not'
    sub2='bad'
    if s.find(sub1) < s.find(sub2):
        s = s[0:int(s.find(sub1))]
        s= s + 'good'
        return s
    else:
        return s

但它不会在末尾产生感叹号。

【问题讨论】:

  • s.replace('not that bad','good')?怎么样
  • 该函数应该适用于任何给定的字符串。因此,如果给定的字符串是“The tea is not that hot”,它将不起作用
  • not that 总是出现在字符串中?你如何找到反义词?你需要一些图书馆。或存储单词的反义词。
  • 你为什么使用 Python 2?此外,您的代码的缩进被破坏了。
  • 这是练习的一部分,有一个单独的代码通过应用参数来检查我的。此外,如果我的缩进被破坏,代码将根本无法工作,但它确实如此。

标签: python string python-2.7 replace indices


【解决方案1】:

您可以在此处使用re

import re
s='This dinner is not that bad!'
re.sub(r'not \w+ bad','good',s)
# 'This dinner is good!'

\w+ - 匹配任何单词字符(等于[a-zA-Z0-9_]

【讨论】:

    【解决方案2】:

    我没有使用正则表达式,因为我真的不知道如何使用。但我的解决方案:

    def not_bad(s):
        sub1='not'
        sub2='bad'
        temp = None
        if s[len(s)-1] == "!": #-> this checks if there is "!"
            temp = s[len(s)-1]
        if s.find(sub1) or s.find(sub2):
            s = s[:int(s.find(sub1))]
            s += 'good'
            if temp:
                s += temp
            return s
        else:
            return s
    

    【讨论】:

    • 你可以写'and'而不是'or',两者都对我有用..但是做你的测试:)希望。我帮助了
    • 有没有办法让函数替换not和bad之间的索引,不管感叹号是什么?
    • 我的代码检查是否有感叹号只是为了知道是否把它放在最后。您可以删除检查是否有感叹号的'if'
    • 如果您只想更改单词“not”,您可以这样做:print(s[s.find(sub1):s.find(sub1)+len(sub1)]) 这将捕获单词“not”的起始索引并从起始索引运行到起始索引 + “不”字的长度。如果你打印它,它会打印'not'。 :) 注意这不是最好的方法,更好的方法是将s.find(sub1) 的返回值保存在一个变量中
    【解决方案3】:

    @ch3ster 是正确的,但那只占一个词。对于更多字符,你应该试试这个

    import re
    
    string1="the dinner is not nice 27 that bad"
    print(re.sub(r"not[a-zA-Z _0-9]*bad","good",string1))
    

    输出

    the dinner is good
    

    【讨论】:

      【解决方案4】:

      请检查一下。

      def not_bad(main_str):
          sub1='not'
          sub2='bad'
          if main_str.find(sub1) < main_str.find(sub2):
              main_str = main_str[0:int(main_str.find(sub1))] + 'good' + main_str[int(main_str.find(sub2)) + len(sub2):]
              return main_str
          else:
              return main_str
      
      
      output_str = not_bad('This dinner is not that bad!')
      print(output_str)
      

      输出:

      This dinner is good!
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-31
        • 2020-11-23
        相关资源
        最近更新 更多