0

For example if I have the word 'House', is there a way to get every possible version of it and set it to an array.

How it would look

word = 'House'

Function does something and the out put would look something like:

word = ['HOUSE', 'House, house', 'hoUse']


  • 3
    I'm curious why you'd ever want such a thing. This is probably an [XY problem](https://meta.stackexchange.com/q/66377/248627). For example, are you trying to accept `yes`, `YES`, `Yes`, etc.? – Chris Jan 06 '20 at 02:20
  • Yes this is why. –  Jan 06 '20 at 02:21
  • 6
    Then take your input and use `.lower()` on it, then compare against `"yes"`. – Chris Jan 06 '20 at 02:21
  • How could this be used in an 'if' statement with an example? –  Jan 06 '20 at 02:22
  • 2
    Or [Ignore case in Python strings](https://stackoverflow.com/q/62567/354577) or [How do I do a case-insensitive string comparison?](https://stackoverflow.com/q/319426/354577) – Chris Jan 06 '20 at 02:27

1 Answers1

0

You can use binary combinations 01110, 00011 etc. with itertools.product() to get every combination of cases with a string. This means setting the 1's as uppercase and the 0's as lowercase. So 01110 -> hOUSe, 00011 -> houSE etc.

from itertools import product

def get_all_cases(string):
    return [
        "".join(
            letter.upper() if binary == 1 else letter
            for letter, binary in zip(string.lower(), binary_comb)
        )
        for binary_comb in product([0, 1], repeat=len(string))
    ]

Output:

>>> get_all_cases("House")
>>> ['house', 'housE', 'houSe', 'houSE', 'hoUse', 'hoUsE', 'hoUSe', 'hoUSE', 'hOuse', 'hOusE', 'hOuSe', 'hOuSE', 'hOUse', 'hOUsE', 'hOUSe', 'hOUSE', 'House', 'HousE', 'HouSe', 'HouSE', 'HoUse', 'HoUsE', 'HoUSe', 'HoUSE', 'HOuse', 'HOusE', 'HOuSe', 'HOuSE', 'HOUse', 'HOUsE', 'HOUSe', 'HOUSE']

You can also just map to True and False boolean values instead of 1 and 0.

from itertools import product

def get_all_cases(string):
    return [
        "".join(
            letter.upper() if is_upper else letter
            for letter, is_upper in zip(string.lower(), comb)
        )
        for comb in product([False, True], repeat=len(string))
    ]
RoadRunner
  • 24,495
  • 6
  • 33
  • 71
  • 2
    Just be warned: if the string is long this will generate a lot of combinations. – nneonneo Jan 06 '20 at 02:35
  • 1
    @nneonneo Yes, 2^n where n is the length of string, to be exact. That being said, this is a slightly convoluted method of doing this. A better use of `itertools.product` is demonstrated in the duplicate question. – Selcuk Jan 06 '20 at 02:37
  • Great example of technically answering the question while ignoring the real problem. – Chris Jan 06 '20 at 02:46
  • @Chris Feel free to downvote if you don't like this answer. – RoadRunner Jan 06 '20 at 02:47
  • Like I said, it technically answers the question. I prefer to let the question be deleted. – Chris Jan 06 '20 at 02:53