Python Forum

Full Version: loop through range until reach size and exclude specific symbol
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
[inline]
string = "ABC_DEF_GH__ILMN_OPQ__RSTUVZ"
index = 14
for i in string:
print([i-5],[i-4],[i-3],[i-2],[i-1],[i],[i+1],[i+2],[i+3],[i+4],[i+5])
[/inline]

output:
F_GH__ILMN_OPQ__R

I need that considering the position of the specific index that I will provide it will go to this index and will print it + 5 characters on the left and 5 on the right excluding the symbol "_".
the final output will be:
FGHILMNOPQR
so I have 5 characters + M +5 characters ( excluding any _ in the count)
with my code I'm able to indicate the index to print( i have not reported the code) but I'm not able to exclude the "_" from the count of the characters to print.
I need something like:
if you find "_" proceeds of one until you reach a length of 5 ( for each side )
Are all letters unique?
actually the real string is made of 4 letters(ACTG):
like:
AAGCTATTGACCTGAAACGATATTG

so you have strings like:

AAG_CTA___TTGA_CCTGAAA_CGA_TATTG
One can combine itertools.islice and comprehension to achieve desired result:

>>> from itertools import islice
>>> s = "ABC_DEF_GH__ILMN_OPQ__RSTUVZ"
>>> i = 14
>>> before = reversed([*islice((char for char in reversed(s[:i]) if char != "_"), 5)])
>>> after = islice((char for char in s[i+1:] if char != "_"), 5)
>>> "".join((*before, s[i], *after))
'FGHILMNOPQR'