Check String is Permutation in Python

  • Post category:String

In this article, you’ll see how to check string is permutation. A permutation is a rearrangement of the letters of a word or phrase. For example, the word “heart” has the following six permutations: “heart”, “earth”, “haert”, “hater”, “rheat”, and “teahr”. To check if two strings are permutations of each other, you can sort the characters in each string and compare the sorted strings.

Step 1: Create two strings

str1 = "abcd"
str2 = "dabc"

print("str1 = ", str1)
print("str1 type = ", type(str1))

print("str2 = ", str2)
print("str2 type = ", type(str2))

Step 2: Check if the string is a permutation

if sorted(str1) == sorted(str2):
    print("Permutation")
else:
    print("Not Permutation")

Output:

str1 =  abcd
str1 type =  <class 'str'>
str2 =  dabc
str2 type =  <class 'str'>
Permutation

Free resources to learn advanced skills: AiHints and CodeAllow