如何查找另一个字符串中是否存在一个字符串字符?

2024-09-24 22:20:18 发布

您现在位置:Python中文网/ 问答频道 /正文

例如:

str1="key" chracters-['k','e','y'] 
str2="hey! let's place a knot" 

结果:True-[因为字符'k','e','y'出现在str2字符串中。]

例2:
str1="pond" characters - ['p','o','n','d'] 
str2="i need some sleep"

结果:True[因为'p','o','n','d'存在于str2]

def findStr(str1,str2):
  count=0
  charArr1 = list(str1.lower())
  charArr2=list(str2.lower())
  for i in range(len(str1)):
    for j in range(len(str2)):
      if charArr1[i] == charArr2[j]:
        count+=1
        break
  if count==(len(charArr1)):
    return True

str1 = input()
str2 = input()
print(findStr(str1,str2))

这个解决方案的问题是,如果str1中有多个相同的字符,那么它将给出错误的答案。
例如:

str1="press" str2="Please repeat!" 

因此,在这种情况下,它应该是false,但我的解决方案将给出true,因为str1有两个"s",而str2只有一个"s"


Tags: intrueforlenifcountrange字符
2条回答
count={}
str1="press"
str2 = "Please repeat!"
for i in str1:
    if i in count:
        count[i]+=1
    else:
        count[i]=1

for j in str2:
    if j in count and count[j] !=0:
        count[j]-=1

for k in count:
    if count[k] != 0:
        print(False)
print(True)

这里有一个解决方案,它也适用于您的第二种情况:

str1="press"
str2="Please repeat!" 
if all(i in str2 for i in str1):
   if all(str1.count(i) == str2.count(i) for i in str1):
        print(True)
   else:
        print(False)
else:
    print(False)

它将o/p:False,因为sstr1中是2倍,而在str2中只有1倍

编辑:

尝试将==更改为<=

 if all(str1.count(i) <= str2.count(i) for i in str1):

相关问题 更多 >