how to use slice to get 1 by 1 loop python

Viewed 23

so i have code using visual basic:

for loop1 = 1 to panjangkata
    sedangolah$ = mid$(kataenkripsi$, loop1, 1)
    for loop2 = 1 to enkrip
        hasilenkrip$ = hasilenkrip$ + sedangolah$
    next loop2
next loop1

how to make to python? i want to crop 1 by 1 and loop it again

example = 0011 -> it can be 00000000 11111111

i just know it must use slice, but what slice?

a[start:stop:step] // like this?
1 Answers

If you want to loop through the characters of the string in variable kataenkripsi and produce an output which repeats each character enkrip times:

kataenkripsi = '0011'
enkrip = 4
hasilenkrip = ''
for a in kataenkripsi:
    hasilenkrip += a * enkrip

print(hasilenkrip)

Produces

0000000011111111

Instead of looping integer indexes and slicing the input string, Python can just use the input as an iterable to produce the individual characters.

If you really want to index,

for loop1 in range(panjangkata):
    sedangolah = kataenkripsi[loop1:loop1+1]
    for loop2 in range(enkrip):
        hasilenkrip = hasilenkrip + sedangolah
Related