Finding all possible case permutations in Python

大兔子大兔子 提交于 2019-12-17 16:49:12

问题


I need to work out a list of all possible permutations of case only in python for example with input of ar it would return [ 'ar','Ar','aR','AR']
or arc [ 'arc','Arc','ARc','aRc','aRC','ARC'] and I know there is likely some Nice method but for the life of me I can not figure it out.


回答1:


def all_casings(input_string):
    if not input_string:
        yield ""
    else:
        first = input_string[:1]
        if first.lower() == first.upper():
            for sub_casing in all_casings(input_string[1:]):
                yield first + sub_casing
        else:
            for sub_casing in all_casings(input_string[1:]):
                yield first.lower() + sub_casing
                yield first.upper() + sub_casing

>>> [x for x in all_casings("foo")]
['foo', 'Foo', 'fOo', 'FOo', 'foO', 'FoO', 'fOO', 'FOO']
>>> list(all_casings("foo"))
['foo', 'Foo', 'fOo', 'FOo', 'foO', 'FoO', 'fOO', 'FOO']


来源:https://stackoverflow.com/questions/6792803/finding-all-possible-case-permutations-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!