如何在另一个字符串中找到一个字符串字符?

2024-09-24 22:31:31 发布

您现在位置: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)

因为s在str1中是2倍,在str2中只有1倍。你知道吗

编辑:

尝试将==更改为<=

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

相关问题 更多 >