Find all upper, lower and mixed case combinations of a string
import itertools
s = 'Fox'
map(''.join, itertools.product(*zip(s.upper(), s.lower())))
>>> ['FOX', 'FOx', 'FoX', 'Fox', 'fOX', 'fOx', 'foX', 'fox']
Find all upper, lower and mixed case combinations of a string that contains numeric and special chars
@Caius's answer works, but it's more efficient to remove the duplicate characters up front instead of waiting until you have all the results and then removing the duplicates there.
The difference in my code is just set((c.upper(), c.lower()))
instead of just (c.upper(), c.lower())
:
import itertools
string = 'abc12@abc.com'
x = map(''.join, itertools.product(*(set((c.upper(), c.lower())) for c in string)))
assert len(list(x)) == 512
Find all lowercase and uppercase combinations of a string in Javascript
One option would be generating capitalization permutations via binary logic.
As a simple example of the snippet below, consider the following table where the left column is the binary representation of the current permutation and the right column is the resulting capitalization:
0000 | word
1000 | Word
0100 | wOrd
1100 | WOrd
...
1111 | WORD
// Used to display the results
const write = (msg) => {
document.body.appendChild(document.createElement('div')).innerHTML = msg;
};
const input = "word";
const letters = input.split("");
const permCount = 1 << input.length;
for (let perm = 0; perm < permCount; perm++) {
// Update the capitalization depending on the current permutation
letters.reduce((perm, letter, i) => {
letters[i] = (perm & 1) ? letter.toUpperCase() : letter.toLowerCase();
return perm >> 1;
}, perm);
const result = letters.join("");
write(result);
}
How to generate all combinations of lower and upper characters in a word?
You can achieve this by zipping the upper and lower case letters and taking their cartesian product:
import itertools
chars = "abc"
results = list(map(''.join, itertools.product(*zip(chars.upper(), chars.lower()))))
print(results)
>>>['ABC', 'ABc', 'AbC', 'Abc', 'aBC', 'aBc', 'abC', 'abc']
To visualise how this works:
zip
is creating our 3 'axes' for us, each with 2 points (the upper / lower cases)[('A', 'a'), ('B', 'b'), ('C', 'c')]
.product
takes the cartesian product of these axes, i.e. the 8 possible coordinates corresponding to the corners of the unit cube it creates:
1. Create axes | 2. Take Cartesian product |
Find all upper,lower combinations of string in Python
There are a few ways of achieving that. Here they are:
1. Changing the case of the string you are searching into:
line[i].lower().find(string.lower())
orline[i].upper().find(string.upper())
Here we're abusing of the immutability of the original strings, since they won't be changed although we apply .upper()
to them, since we're not doing any assignment.2. using the re
module would also be helpful:
import re
re.search('all', line[0], re.IGNORECASE)
orre.search('(?i)all',line[0])
Find all upper/lower/mixed combinations of a string
You can use recursive generator. The first parameter contains left part of the string generated so far, and the second parameter is the remaining right part of the original string.
function combinations(s1, s2)
if s2:len() > 0 then
local c = s2:sub(1, 1)
local l = c:lower()
local u = c:upper()
if l == u then
combinations(s1 .. c, s2:sub(2))
else
combinations(s1 .. l, s2:sub(2))
combinations(s1 .. u, s2:sub(2))
end
else
print(s1)
end
end
So the function is called in this way.combinations("", "ABC_-123")
You only have to store intermediate results instead of printing them. PHP - all combination upper and lower case characters of string
A bit of a code dump with some comments thrown in for good measure. This was converted from the Java implementation - https://stackoverflow.com/a/6785649/296555
http://sandbox.onlinephpfunctions.com/code/aadefa26561a0e33c48fd1d147434db715c8fc59
November 2020 - This answer has was updated in 2 places. See the revision history for details.
<?php
function calculatePermutations($text) {
$permutations = array();
$chars = str_split($text);
// Count the number of possible permutations and loop over each group
for ($i = 0; $i < 2 ** strlen($text); $i++) {
// Loop over each letter [a,b,c] for each group and switch its case
for ($j = 0; $j < strlen($text); $j++) {
// isBitSet checks to see if this letter in this group has been checked before
// read more about it here: http://php.net/manual/en/language.operators.bitwise.php
$permutations[$i][] = (isBitSet($i, $j))
? strtoupper($chars[$j])
: $chars[$j];
}
}
return $permutations;
}
function isBitSet($n, $offset) {
return ($n >> $offset & 1) != 0;
}
print_r(calculatePermutations('abc'));
Finding all possible case permutations in Python
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']
How to get every combination of a string?
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))
]
Related Topics
How to Fix Selenium Webdriverexception: the Browser Appears to Have Exited Before We Could Connect
How Does the Max() Function Work on List of Strings in Python
How to Obscure a Line Behind a Surface Plot in Matplotlib
Quickest Way to Make a Get_Dummies Type Dataframe from a Column with a Multiple of Strings
Asyncio Cancellederror and Keyboardinterrupt
How to Set a Proxy for Phantomjs/Ghostdriver in Python Webdriver
Error Importing Scikit-Learn Modules
How to Check If Two Strings Are Anagrams of Each Other
Python Decompression Relative Performance
Handling of Duplicate Indices in Numpy Assignments
Importing Class from Another File
Most Efficient Way to Sort an Array into Bins Specified by an Index Array
How to Use Digit Separators for Python Integer Literals
Python Pandas, Write Dataframe to Fixed-Width File (To_Fwf)
Saving Plots (Axessubplot) Generated from Python Pandas with Matplotlib's Savefig
Writing Unit Tests in Python: How to Start
Row-Wise Average for a Subset of Columns with Missing Values