我對以下代碼有疑問:
str1 = "Race"
str2 = "Care"
# convert both the strings into lowercase
str1 = str1.lower()
str2 = str2.lower()
# check if length is same
if(len(str1) == len(str2)):
# sort the strings
sorted_str1 = sorted(str1)
sorted_str2 = sorted(str2)
# if sorted char arrays are same
if(sorted_str1 == sorted_str2):
print(str1 " and " str2 " are anagram.")
else:
print(str1 " and " str2 " are not anagram.")
else:
print(str1 " and " str2 " are not anagram.")
"Race"而"Care"現在字謎,但如何使句子字謎?
例如:
str1 = "Race is good"
str2 = "Careisgood"
它們也是字謎,但它表明它不是字謎。我認為這是因為空間。如何跳過空格?
uj5u.com熱心網友回復:
要從字串中洗掉空格,您可以使用 replace(" ", "") 方法。
str1 = "Race is good"
str2 = "Careisgood"
# convert both the strings into lowercase
str1 = str1.lower().replace(" ", "")
str2 = str2.lower().replace(" ", "")
# check if length is same
if(len(str1) == len(str2)):
# sort the strings
sorted_str1 = sorted(str1)
sorted_str2 = sorted(str2)
# if sorted char arrays are same
if(sorted_str1 == sorted_str2):
print(str1 " and " str2 " are anagram.")
else:
print(str1 " and " str2 " are not anagram.")
else:
print(str1 " and " str2 " are not anagram.")
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/365136.html
標籤:Python
上一篇:Pandas將行作為新列加入
下一篇:關于另一列如何填充NA?
