![]() |
loop through range until reach size and exclude specific symbol - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: loop through range until reach size and exclude specific symbol (/thread-21274.html) |
loop through range until reach size and exclude specific symbol - pino88 - Sep-22-2019 [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 ) RE: loop through range until reach size and exclude specific symbol - perfringo - Sep-22-2019 Are all letters unique? RE: loop through range until reach size and exclude specific symbol - pino88 - Sep-22-2019 actually the real string is made of 4 letters(ACTG): like: AAGCTATTGACCTGAAACGATATTG so you have strings like: AAG_CTA___TTGA_CCTGAAA_CGA_TATTG RE: loop through range until reach size and exclude specific symbol - perfringo - Sep-23-2019 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' |