This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 6 years ago.
For example, suppose we have a string:
'abcdefg'
And we need to get a list like this:
['ab', 'bc', 'cd', 'de', 'ef', 'fg']
we should not use any kind of library
Here is my solution:
def str_split(s):
s = iter(s)
ch1=''
ch2=''
chars_list=[]
while True:
try:
ch1 = ch2 or next(s)
ch2 = next(s)
chars_list.append(ch1 + ch2)
except:
break
return chars_list
I wonder is there a better solution? Maybe it is possible to use list comprehension like here?
You can simply use zip() and a list comprehension:
chars_list = [ch1 + ch2 for ch1, ch2 in zip(s, s[1:])]
More generally, if you need a solution for any n:
n = 3
chars_list = [s[i:i+n] for i in range(0, len(s) - n + 1, n - 1)]
# ['abc', 'cde', 'efg']
You could try this (hacky) solution:
def str_split(s):
return [s[start:end] for start, end in enumerate(range(2, len(s)+1))]
Delgan's zipping solution seems more elegant though :)
Related
This question already has answers here:
if/else in a list comprehension
(12 answers)
Closed 1 year ago.
I have a list of strings
str_list = ['a', 'b', 'c']
and want to add a suffix
suffix = '_ok'
when the string value is 'a'.
This works:
new_str_list = []
for i in str_list:
if i == 'a':
new_str_list.append(i + suffix)
else:
new_str_list.append(i)
new_str_list
# ['a_ok', 'b', 'c']
How can I simplify this with a list comprehension?
Something like
new_str_list = [i + suffix for i in str_list if i=='a' ....
[i + suffix if i == 'a' else i for i in str_list]
Putting if after the for as you tried is for skiping values.
In your case you don't skip values but process them differently.
Create the item according to it's value -
[i + suffix if i=='a' else i for i in str_list ]
A concise option making use of fact that False == 0:
[i + suffix * (i=='a') for i in str_list]
This question already has answers here:
Removing duplicate characters from a string
(15 answers)
Closed 2 years ago.
I have a list l = ['AAB', 'CAA', 'ADA'] . I want to get the following list without duplicated characters new_l = ['AB','CA','AD']. I am trying to iterate on a nested loop but I'm not sure this is the best way to accomplish this. here is my try:
new_l = []
for i in range(0,len(l)-1):
for j in range(0,len(l)-1):
if l[i][j] != l[i+1][j+1]:
new_l = ..............
Can someone help me on how to get a set by iterating over every element of this list of strings ?
You can easily do it, since a string is also a list.
strl = ['AAB', 'CAA', 'ADA']
new_strl = []
for s in strl:
new_strl.append("".join(set(s)))
print(new_strl)
Set can mess order of characters. Better use OrderedDict:
from collections import OrderedDict
strl = ['AAB', 'CAA', 'ADA']
result = ["".join(OrderedDict.fromkeys(s)) for s in strl]
l = ['AAB', 'CAA', 'ADA']
new_l = [''.join(sorted(set(x))) for x in l]
#op
['AB', 'AC', 'AD']
This question already has answers here:
Is there a zip-like function that pads to longest length?
(8 answers)
Closed 3 years ago.
I know a way to interleave two strings using Python but it works only if their lengths are equal:
u = 'Abcd'
l = 'Wxyz'
res = "".join(i + j for i, j in zip(u, l))
print(res)
This will give me the correct Output:AWbxcydz
But if the strings are u = 'Utkarsh' and l = 'Jain', the same method does not give the correct answer. Can someone suggest a way to do so?
Use zip_longest from itertools.
from itertools import zip_longest
u = 'Abcdefgh'
l = 'Wxyz'
res = "".join(i + j for i, j in zip_longest(u, l, fillvalue=''))
print(res)
This question already has answers here:
Converting a list to a string [duplicate]
(8 answers)
How to convert list to string [duplicate]
(3 answers)
Closed 9 years ago.
I am trying, in the following code, to encrypt a message. The problem is that my result comes up in a list format instead of a string. How do I make it into a string?
You need to flatten the nested lists in your result and then turn it into a string. Here's one way to do it:
>>> import itertools
>>> result = [['I', 'R', 'A', ' ', 'O'], [' ', 'E', 'D', 'Y', 'U']]
>>> ''.join(itertools.chain(*result))
'IRA O EDYU'
finalArray is clearly a list:
finalArray = []
To convert it to a string, use join:
print ''.join(finalArray)
But first, you probably do not want these nested lists. You should use extend, not append:
def stringEncrypter(A):
length = len(A)
finalArray = []
if length%2 == 0:
firstArray=[]*(length/2)
secondArray=[]*(length/2)
else:
firstArray=[]*((length+1)/2)
secondArray=[]*((length-1)/2)
for x in range(0, length-1):
if x%2 == 0:
firstArray.append(A[x:x+1])
secondArray.append(A[x+1:x+2])
finalArray.extend(firstArray)
finalArray.extend(secondArray)
print ''.join(finalArray)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Pythonic way to insert every 2 elements in a string
I'll be happy if someone can help with python code))
How can I put the space into a string
for example,
If there is the string 'akhfkahgdsds'
I would like to turn it into 'ak hf ka hg ds ds'
>>> s = 'akhfkahgdsds'
>>> range(0, len(s), 2) # gives you the start indexes of your substrings
[0, 2, 4, 6, 8, 10]
>>> [s[i:i+2] for i in range(0, len(s), 2)] # gives you the substrings
['ak', 'hf', 'ka', 'hg', 'ds', 'ds']
>>> ' '.join(s[i:i+2] for i in range(0, len(s), 2)) # join the substrings with spaces between them
'ak hf ka hg ds ds'
def isection(itr, size):
while itr:
yield itr[:size]
itr = itr[size:]
' '.join(isection('akhfkahgdsds', 2))
I don't really think this is the way to go here, but I think this answer is kind of fun anyway. If the length of the string is always even, you can play neat tricks with iter -- if it's odd, the last character will be truncated:
s = '11223344'
i_s = iter(s)
' '.join(x+next(i_s) for x in i_s)
Of course, you can always pad it:
i_s = iter(s+len(s)%2*' ')
you can try this simple code:
try:
for i in range(0,len(s)+1,2):
print s[i]+s[i+1],
except IndexError:
pass