1

I am wanting to loop through a string and capture 2 items each time while also incrementing through the index of the iterable. So I want to slice 2 items but increase the index by 1 every time through the loop. How can I do this?

my_string = 'teststring'

desired output = te es st ts st tr ri in ng

I have tried the following to slice the two items, but can't figure out the best way to iterate thought the index

str1 = 'teststring'
i=0
while i<10: 
    i +=1
    str2=str1[0:2]
    print(str2)
Soupy
  • 13
  • 1
  • 4

5 Answers5

2

Here is a possible solution (s is your string):

for j in range(len(s) - 1):
    print(s[j:j + 2])

Another one:

for c1, c2 in zip(s[:-1], s[1:]):
    print(c1 + c2)
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
1
str1 = 'teststring'
result = []
for i in range(len(str1) - 1):
    result.append(str1[i:i + 2])

print(result)

output

['te', 'es', 'st', 'ts', 'st', 'tr', 'ri', 'in', 'ng']
Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
1

By using list comprehension you can do this in a one-liner

s = 'teststring'

r = ' '.join([s[i:i+2] for i in range(len(s)-1)])

print(r)
Daniel F
  • 13,684
  • 11
  • 87
  • 116
-1

Since you are trying to move both the start and end point of the slice with each iteration, you want to use the index+length of slice for the end point.

You should iterate after the slice is done. Here is the answer with minimal changes to your code:

str1 = 'teststring'
i=0
while i<=len(str1)-2: 
    str2=str1[i:i+2]
    i += 1
    print(str2)
-1

I would use a for loop instead of a while loop, like this:

def strangeSlice(string):
    out = ""
    for i in range(len(string)-1):
        out += string[i:i+2]
        if i != len(string)-2:
            out += " "
    print(out)
    return out
def main():
    strangeSlice("teststring")
main() #you need to call the main function to run
kenntnisse
  • 429
  • 2
  • 12