python - 如何检查2个字符串是否具有相同的字符?- Python
问题描述
我想检查 2 个字符串是否有相同的字符?
比如:
“aand”和“daan” => true
“aafw”和“kaaw” => false
这是我的代码:
def procedures(txt1, txt2):
str1 = txt1.lower()
str2 = txt2.lower()
for i in str1:
for j in str2:
if i == j:
str1.replace(i, "", 1)
str2.replace(i, "", 1)
print("did")
if str1 == "" and str2 == "":
return True
else:
return False
但它False
返回alii
and liai
!
我所做的?
解决方案
您可以像遍历列表/元组一样遍历 python 字符串。一个简单的功能是:
def stringCompare(a, b):
for i in a:
if i not in b:
return False
return True
print(stringCompare("aand", "daan"))
>> True
print(stringCompare("aafw", "kaaw"))
>> False
print(stringCompare("alii", "liai"))
>> True
请注意,上述函数仅检查两个字符串中的所有字符是否相等。现在,为了检查出现次数,您可以使用collections
as:
from collections import Counter
def stringCompare2(a, b):
# also compares the occurance
occurance_dict_a = Counter(a)
occurance_dict_b = Counter(b)
return occurance_dict_a == occurance_dict_b
print(stringCompare2("abc", "aabc"))
>> False
print(stringCompare2("abc", "cba"))
>> True
推荐阅读
- google-cloud-platform - GCE 入口健康检查在 kubernetes 上失败
- android - 在尝试检索图像时获取类未找到异常以及无法解码流异常
- ios - 如何在目标 c 中设备旋转后更新 Web 视图宽度?
- c++ - 如何存储具有多个空格的字符串c ++
- java - 警报 Dialog.Builder(??)
- go - 返回 nil 结构而不是空结构 go-gorm
- ios - 此 iPhone 运行 iOS 12.0 (16A366),此版本的 Xcode 可能不支持
- android - 在调试模式下更新 Firebase Analytics 中的 UserProperties
- amazon-web-services - 通过 AWS 请求 ID 获取请求参数
- django-viewflow - 跳转到上一个任务导致任务没有 flow_task 和进程