sci-guy
sci-guy

Reputation: 2584

Slicing a string with a list as input

I have a list:

my_list = [6, 9, 12]

I have a string:

my_string = "The quick brown fox jumps over the lazy dog."

I want to slice the string as such:

my_string[:6]
my_string[6:9]
my_string[9:12]
my_string[12:]

Notice that the slice range are the elements of my_list.

Output:

The qu
ick
 br
own fox jumps over the lazy dog.

Or into a list. But, I am struggling with an algorithm that does the slicing.

Upvotes: 0

Views: 156

Answers (5)

iGian
iGian

Reputation: 11193

You could write a function which returns a generator, to be used wherever you need to present the result.

def slice_string_by(my_string, my_list):
  memo = 0
  for idx in my_list:
    size = idx - memo
    chunck = my_string[0:size]
    yield chunck
    my_string = my_string[size:]
    memo = idx
  yield my_string


Then you can just call:

res = slice_string_by(my_string, my_list)

The result is a generator, converting to a list you get:

list(res) #=> ['The qu', 'ick', ' br', 'own fox jumps over the lazy dog.']


Or you can just iterate over it to print the elements:

for chunk in slice_string_by(my_string, my_list):
  print(chunk)

# The qu
# ick
#  br
# own fox jumps over the lazy dog.

Upvotes: 0

Tojra
Tojra

Reputation: 683

My solution

L=[0]+my_list+[len(my_string)]
for a in range(len(L)-1):
    print(my_string[L[a]:L[a+1]])

Upvotes: 2

AKSHAY V MADALGI
AKSHAY V MADALGI

Reputation: 68

This worked according to output required

my_list = [6, 9, 12]

my_string = "The quick brown fox jumps over the lazy dog."

resultstring = ''

temp = 0

for i in range(0,len(my_list)):
    resultstring+=my_string[temp:my_list[i]]
    resultstring+='\n'
    temp = my_list[i]

resultstring+=my_string[temp:]

print resultstring

Output:

The qu
ick
 br
own fox jumps over the lazy dog.

Upvotes: 0

Austin
Austin

Reputation: 26039

Use zip and slicing. Modify your my_list by adding a 0 at the beginning prior to applying zip and slice:

my_list = [6, 9, 12]
my_string = "The quick brown fox jumps over the lazy dog."

my_list = [0] + my_list
for x, y in zip(my_list, my_list[1:]):
    print(my_string[x: y])

print(my_string[my_list[-1]:])

# The qu
# ick                                                          
# br                                                         
# own fox jumps over the lazy dog.

Or rather if you need my_list to be unchanged for some reason, use a separate variable here: my_list1 = [0] + my_list and for x, y in zip(my_list1, my_list1[1:]):.

Upvotes: 2

Rick
Rick

Reputation: 57

my_list = [6, 9, 12]
my_string = "The quick brown fox jumps over the lazy dog."
start = 0
for end in my_list:
    print(my_string[start:end])
    start = end
print(my_string[end:])

Worked for me...

Upvotes: 1

Related Questions