📜  Python – 相似字符字符串比较

📅  最后修改于: 2022-05-13 01:55:01.527000             🧑  作者: Mango

Python – 相似字符字符串比较

给定两个用 delim 分隔的字符串,检查两者是否包含相同的字符。

方法 #1:使用 sorted() + split()

在此,我们使用 split() 执行拆分,然后执行排序任务以按顺序获取字符串,然后使用运算符比较字符串。

Python3
# Python3 code to demonstrate working of 
# Similar characters Strings comparison
# Using split() + sorted()
  
# initializing strings
test_str1 = 'e:e:k:s:g'
test_str2 = 'g:e:e:k:s'
  
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
  
# initializing delim 
delim = ':'
  
# == operator is used for comparison
res = sorted(test_str1.split(':')) == sorted(test_str2.split(':'))
      
# printing result 
print("Are strings similar : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Similar characters Strings comparison
# Using set() + split()
  
# initializing strings
test_str1 = 'e:k:s:g'
test_str2 = 'g:e:k:s'
  
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
  
# initializing delim 
delim = ':'
  
# == operator is used for comparison
# removes duplicates and compares
res = set(test_str1.split(':')) == set(test_str2.split(':'))
      
# printing result 
print("Are strings similar : " + str(res))


输出
The original string 1 is : e:e:k:s:g
The original string 2 is : g:e:e:k:s
Are strings similar : True

方法 #2:使用 set() + split()

在此,我们将字符串转换为 set(),而不是 sort(),以获取排序。这仅字符串。

Python3

# Python3 code to demonstrate working of 
# Similar characters Strings comparison
# Using set() + split()
  
# initializing strings
test_str1 = 'e:k:s:g'
test_str2 = 'g:e:k:s'
  
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
  
# initializing delim 
delim = ':'
  
# == operator is used for comparison
# removes duplicates and compares
res = set(test_str1.split(':')) == set(test_str2.split(':'))
      
# printing result 
print("Are strings similar : " + str(res)) 
输出
The original string 1 is : e:k:s:g
The original string 2 is : g:e:k:s
Are strings similar : True