![](/img/trans.png)
[英]How can I check if a string has the same characters? Python
[英]how to check if 2 string have same characters or no? - python
我想檢查 2 個字符串是否有相同的字符?
喜歡:
"aand" 和 "daan" => true
“aafw”和“kaaw”=>假
這是我的代碼:
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
但它為alii
和liai
返回False
!
我所做的?
您可以像遍歷列表/元組一樣遍歷 python 字符串。 一個簡單的 function 將是:
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
注意上面的 function 只檢查兩個字符串中的所有字符是否相等。 現在,為了檢查出現次數,您可以使用collections
作為:
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
這是一個眾所周知的問題,有許多可能的解決方案。 嘗試這個:
def procedures(txt1, txt2):
return sorted(txt1) == sorted(txt2)
Str 對象不可編輯。 所以str.replace
方法返回一個新字符串。 您必須分配給str1
和str2
結果。 所以你的代碼現在必須是這樣的:
def procedures(txt1, txt2):
str1 = txt1.lower()
str2 = txt2.lower()
for i in str1:
for j in str2:
if i == j:
str1 = str1.replace(i, "", 1)
str2 = str2.replace(j, "", 1)
print("did")
if str1 == "" and str2 == "":
return True
else:
return False
或者您可以從原始字符串中列出字符並對其進行排序。 因此,如果字符串具有相同的字符,它們將被轉換為相同的字符序列(列表)。
def procedures(txt1, txt2):
seq1 = list(txt1.lower())
seq2 = list(txt2.lower())
seq1.sort()
seq2.sort()
if seq1 == seq2:
return True
else:
return False
您是否考慮了出現次數? 如果是這樣,可以想象將每個 str 變成一個字符列表,然后對每個列表進行排序。 然后將繼續比較這些列表。
def procedures(txt1, txt2):
str1 = txt1.lower()
str2 = txt2.lower()
str1 = list(str1)
result = False
for dt in str1:
if dt in str2:
result = True
else:
result = False
return result
print(procedures('neeraj','prakash'))
print(procedures('neeraj','neeraj'))
您必須為第一個文本創建一個列表,然后使用循環在第二個 str 中逐個檢查。 而已。
首先,我們對兩個字符串進行排序。 第二比較它們。
def equal(a,b):
a = sorted(a)
b = sorted(b)
if a == b:
return True
return False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.