Adding two items at a time in a list comprehension
You can start with this:
print list( '^'.join(mystring.lower()) )
which gives:
['a', '^', 'b', '^', 'c', '^', ...]
So this would give the desired output:
l = list( '^'.join(mystring.lower()) )
l.insert(0, '^')
print l
And another way:
print [ y for x in zip(['^'] * len(mystring), mystring.lower()) for y in x ]
which gives:
['^', 'a', '^', 'b', '^', 'c', ...
You can use itertools.chain.from_iterable
, this is equivalent to that nested list comprehension version but slightly efficient(for large lists):
>>> from itertools import chain
>>> mystring = 'ABCELKJSDLHFWEHSJDHFKHIUEHFSDF'
>>> list(chain.from_iterable([['^', x] for x in mystring]))
['^', 'A', '^', 'B', '^', 'C', '^', 'E', '^', 'L', '^', 'K', '^', 'J', '^', 'S', '^', 'D', '^', 'L', '^', 'H', '^', 'F', '^', 'W', '^', 'E', '^', 'H', '^', 'S', '^', 'J', '^', 'D', '^', 'H', '^', 'F', '^', 'K', '^', 'H', '^', 'I', '^', 'U', '^', 'E', '^', 'H', '^', 'F', '^', 'S', '^', 'D', '^', 'F']
In Python 3.3+ you can also use yield from
in a generator function:
>>> mystring = 'ABCELKJSDLHFWEHSJDHFKHIUEHFSDF'
>>> def solve(strs):
... for x in strs:
... yield from ['^', x]
...
>>> list(solve(mystring))
['^', 'A', '^', 'B', '^', 'C', '^', 'E', '^', 'L', '^', 'K', '^', 'J', '^', 'S', '^', 'D', '^', 'L', '^', 'H', '^', 'F', '^', 'W', '^', 'E', '^', 'H', '^', 'S', '^', 'J', '^', 'D', '^', 'H', '^', 'F', '^', 'K', '^', 'H', '^', 'I', '^', 'U', '^', 'E', '^', 'H', '^', 'F', '^', 'S', '^', 'D', '^', 'F']