0

I am making a python program where I need to inspect individual four letter parts of a variable. If the variable is for example help_me_code_please it should output ease then e_pl etc , I attempted it with

a=0
b=3
repetitions=5
word="10011100110000111010"
for x in range (1,repetitions):        
    print(word[a:b])
    a=a+4
    b=b+4 

however it just outputs empty lines. Thanks so much for any help in advanced.

3 Answers3

0

This should work:

words = "help_me_code_please"
size = 4
start = len(words)%size - size

for i in reversed(range(start, len(words), size)):
    print(words[max(0,i):i+size])

output is

ease
e_pl
_cod
p_me
hel

Explanation: start gives us a starting point, that is some divisible block away from the length of our string (words). In our example, it's -1, as that is 20 (5*4) away from 19, the length of words.

Now we do a reverse loop, from 19 -> -1 at size four. So we go 15, 11, 7, 3, -1. Within each loop, we print from our position to the position + 4. So the first loop iteration prints out words[15:19] which outputs ease, the second is words[11:15], etc etc. This results in the output we see.

Hopefully this explanation makes sense!

Peter Dolan
  • 1,393
  • 1
  • 12
  • 26
0

Assuming you want print the word backwards with a repetition of 4.

word = 'help_me_code_please'

# Looping from backwards on the word with a step of 4
for i in range(len(word)-1, -1, -4):
    # j is the starting point from where we have to print the string.
    j = i-3 if i > 3 else i-1
    print word[j:i+1]
0

For forward:

[word[4*l:4*(l+1)] for l in range(0, int(len(word)/4)+1)]
['help', '_me_', 'code', '_ple', 'ase']

For backward:

[word[::-1][4*l:4*(l+1)][::-1] for l in range(0, int(len(word)/4)+1)]
['ease', 'e_pl', '_cod', 'p_me', 'hel']

This is list comprehensions (https://docs.python.org/3.6/tutorial/datastructures.html#list-comprehensions), you can iterate the resulting list.

Its var[start:ends:step]. word[::-1] means get a letter, start at the beginning, finish at the end, and advance -1 steps, so it reverse the string

For the new values:

word="10011100110000111010"
[word[4*l:4*(l+1)] for l in range(0, int(len(word)/4)+1)]
['1001', '1100', '1100', '0011', '1010']

[word[::-1][4*l:4*(l+1)] for l in range(0, int(len(word)/4)+1)]
['0101', '1100', '0011', '0011', '1001']
Xavier
  • 106
  • 4