【问题标题】:find a substring in a string python在字符串python中查找子字符串
【发布时间】:2016-10-09 03:00:12
【问题描述】:

这可能是一个初学者的问题,但我似乎无法在任何地方找到答案

如何从字符顺序不同的另一个字符串中搜索并返回子字符串?

当我检查下面的代码时,它似乎给出了正确的答案,但我试图打印它而不是得到 True 或 False,而且,当我提交它时,它显示“不正确。您的提交没有返回正确的输入的结果('UdaciousUdacitee','Udacity')。您的提交通过了 4 个测试用例中的 3 个:“....我很困惑..我已经绞尽脑汁 3 个小时左右。

谢谢

Test case 1: False 
Test case 2: True 
Test case 3: True 
Test case 4: True

更准确地说:

def fix_machine(debris, product):
  if debris.find(product):
   return product
  else:
   print("Give me something that's not useless next time.")


print "Test case 1: ", fix_machine('UdaciousUdacitee', 'Udacity') == "Give me something that's not useless next time."
print "Test case 2: ", fix_machine('buy me dat Unicorn', 'Udacity') == 'Udacity'
print "Test case 3: ", fix_machine('AEIOU and sometimes y... c', 'Udacity') == 'Udacity'
print "Test case 4: ", fix_machine('wsx0-=mttrhix', 't-shirt') == 't-shirt'

【问题讨论】:

  • 到目前为止你尝试过什么? Stack Overflow 不是让其他人为您编写代码的好地方。

标签: python string substring


【解决方案1】:

您正在 print() 处理 else 案例。我认为您的意思是返回该字符串。 (至少根据你的断言代码)

【讨论】:

    【解决方案2】:

    你用错了str.find()

    "It determines if string str occurs in string, or in a substring of string if starting index beg and ending index end are given."
    

    它会考虑顺序,这不是你想要的。将您的 fix_machine 更改为:

    def fix_machine(debris, product):
      charNumInDebris = dict()
      charNumInProduct = dict()
    
      for c in debris:
        if c in charNumInDebris:
          charNumInDebris[c] += 1
        else:
          charNumInDebris[c] = 1
    
      for c in product:
        if c in charNumInProduct:
          charNumInProduct[c] += 1
        else:
          charNumInProduct[c] = 1
    
      for c in charNumInProduct:
        if not (c in charNumInDebris and charNumInDebris[c] >= charNumInProduct[c]):
          return "Give me something that's not useless next time."
    
      return product
    

    【讨论】:

      猜你喜欢
      • 2021-08-13
      • 2023-04-03
      • 2014-02-27
      • 2011-07-13
      • 1970-01-01
      • 2010-10-21
      • 1970-01-01
      相关资源
      最近更新 更多