使用Python中的内置函数对给定的字符串进行排列

在本教程中,我们会发现使用的内置函数的字符串的排列Python的 所谓排列。方法排列 itertools模块中。阅读文章以了解什么是排列。

查找字符串置换的过程

  • 导入itertools 模块。

  • 初始化字符串。

  • 使用itertools.permutations方法查找字符串的排列。

  • 在第三步中,该方法返回一个对象并将其转换为列表。

    • 列表包含字符串的排列作为元组。

示例

让我们看一下程序。

## importing the module
import itertools
## initializing a string
string = "XYZ"
## itertools.permutations method
permutaion_list = list(itertools.permutations(string))
## printing the obj in list
print("-----------Permutaions Of String In Tuples----------------")
print(permutaion_list)
## converting the tuples to string using 'join' method
print("-------------Permutations In String Format-----------------")
for tup in permutaion_list:
   print("".join(tup))

输出结果

如果运行上述程序,将得到以下结果。

-----------Permutaions Of String In Tuples----------------
[('X', 'Y', 'Z'), ('X', 'Z', 'Y'), ('Y', 'X', 'Z'), ('Y', 'Z', 'X'), ('Z', 'X', 'Y'), ('Z', 'Y', 'X')]
-------------Permutations In String Format-----------------
XYZ
XZY
YXZ
YZX
ZXY
ZYX

如果您对该程序有任何疑问,请在评论部分中提及它们。