在字符串python中查找子字符串

时间:2016-10-09 03:00:13

标签: python string substring

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

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

当我检查下面的代码时,它似乎给出了正确的答案,但我试图打印它而不是正确或错误,而且,当我提交它时,它说"不正确。您的提交未返回输入的正确结果(' 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'

2 个答案:

答案 0 :(得分:0)

你是print() else案件。我想你的意思是返回那个字符串。 (至少根据你的断言代码)

答案 1 :(得分:0)

您使用了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