Adding spaces to string based on list

VNG*_*NGu 3 python split list

I have a string s and a list of strings, arr. The length of s is equal to the total length of strings in arr. I need to split s into a list, such that each element in the list has the same length as the corresponding element in arr.

For example:

s = 'Pythonisanprogramminglanguage'

arr = ['lkjhgf', 'zx', 'qw', 'ertyuiopakk', 'foacdhlc']
Run Code Online (Sandbox Code Playgroud)
s = 'Pythonisanprogramminglanguage'

arr = ['lkjhgf', 'zx', 'qw', 'ertyuiopakk', 'foacdhlc']
Run Code Online (Sandbox Code Playgroud)

Aja*_*234 18

使用iter起来更清洁next

s = 'Pythonisanprogramminglanguage'
arr = ['lkjhgf', 'zx', 'qw', 'ertyuiopakk', 'foacdhlc']
new_s = iter(s)
result = [''.join(next(new_s) for _ in i) for i in arr]
Run Code Online (Sandbox Code Playgroud)

输出:

['Python', 'is', 'an', 'programming', 'language']
Run Code Online (Sandbox Code Playgroud)


Sim*_*mon 5

One way would be to do this:

s = 'Pythonisanprogramminglanguage'

arr = ['lkjhgf', 'zx', 'qw', 'ertyuiopakk', 'foacdhlc']

expected = []
i = 0
for word in arr:
    expected.append(s[i:i+len(word)])
    i+= len(word)

print(expected)
Run Code Online (Sandbox Code Playgroud)


sek*_*kky 5

Using a simple for loop this can be done as follows:

s = 'Pythonisanprogramminglanguage'

arr = ['lkjhgf', 'zx', 'qw', 'ertyuiopakk', 'foacdhlc']

start_index = 0
expected = list()
for a in arr:
    expected.append(s[start_index:start_index+len(a)])
    start_index += len(a)

print(expected)
Run Code Online (Sandbox Code Playgroud)