Adding spaces to string based on listHow do I check if a list is empty?Finding the index of an item given a list containing it in PythonHow do I iterate over the words of a string?What is the difference between Python's list methods append and extend?How do you split a list into evenly sized chunks?Convert bytes to a string?How do I split a string on a delimiter in Bash?How to make a flat list out of list of listsHow to clone or copy a list?Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?

Java Servlet & JSP simple login

The usage of kelvin in formulas

How can one's career as a reviewer be ended?

Can a human be transformed into a Mind Flayer?

Does putting salt first make it easier for attacker to bruteforce the hash?

Who is "He that flies" in Lord of the Rings?

Was planting UN flag on Moon ever discussed?

Is using 'echo' to display attacker-controlled data on the terminal dangerous?

empApi with Lightning Web Components?

What is the color of artificial intelligence?

Is it okay to have a sequel start immediately after the end of the first book?

Should I put programming books I wrote a few years ago on my resume?

What would prevent chimeras from reproducing with each other?

How do i export activities related to an account with a specific recordtype?

What does the pair of vertical lines in empirical entropy formula mean?

Is it possible to have 2 different but equal size real number sets that have the same mean and standard deviation?

Proving that a Russian cryptographic standard is too structured

bash vs. zsh: What are the practical differences?

Non-aqueous eyes?

Printing Pascal’s triangle for n number of rows in Python

Why are MBA programs closing in the United States?

How can I make 12 tone and atonal melodies sound interesting?

Does a bank have to tell me if a check made out to me was cashed there?

Why does smartdiagram replace the Greek letter xi by a number?



Adding spaces to string based on list


How do I check if a list is empty?Finding the index of an item given a list containing it in PythonHow do I iterate over the words of a string?What is the difference between Python's list methods append and extend?How do you split a list into evenly sized chunks?Convert bytes to a string?How do I split a string on a delimiter in Bash?How to make a flat list out of list of listsHow to clone or copy a list?Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








8















I have the string and array.
String have the same amount of alphabetic character like array.
I need to split s to list that have equal lenght of each element like arr.



s = 'Pythonisanprogramminglanguage'

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


expected == ['Python', 'is', 'an', 'programming', 'language']









share|improve this question



















  • 8





    What have you tried so far?

    – Klaus D.
    May 25 at 14:08






  • 3





    Off topic but, python is a programming language.

    – Tvde1
    May 26 at 11:47

















8















I have the string and array.
String have the same amount of alphabetic character like array.
I need to split s to list that have equal lenght of each element like arr.



s = 'Pythonisanprogramminglanguage'

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


expected == ['Python', 'is', 'an', 'programming', 'language']









share|improve this question



















  • 8





    What have you tried so far?

    – Klaus D.
    May 25 at 14:08






  • 3





    Off topic but, python is a programming language.

    – Tvde1
    May 26 at 11:47













8












8








8








I have the string and array.
String have the same amount of alphabetic character like array.
I need to split s to list that have equal lenght of each element like arr.



s = 'Pythonisanprogramminglanguage'

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


expected == ['Python', 'is', 'an', 'programming', 'language']









share|improve this question
















I have the string and array.
String have the same amount of alphabetic character like array.
I need to split s to list that have equal lenght of each element like arr.



s = 'Pythonisanprogramminglanguage'

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


expected == ['Python', 'is', 'an', 'programming', 'language']






python list split






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 25 at 16:59









martineau

72.5k1094191




72.5k1094191










asked May 25 at 14:04









VNGuVNGu

553




553







  • 8





    What have you tried so far?

    – Klaus D.
    May 25 at 14:08






  • 3





    Off topic but, python is a programming language.

    – Tvde1
    May 26 at 11:47












  • 8





    What have you tried so far?

    – Klaus D.
    May 25 at 14:08






  • 3





    Off topic but, python is a programming language.

    – Tvde1
    May 26 at 11:47







8




8





What have you tried so far?

– Klaus D.
May 25 at 14:08





What have you tried so far?

– Klaus D.
May 25 at 14:08




3




3





Off topic but, python is a programming language.

– Tvde1
May 26 at 11:47





Off topic but, python is a programming language.

– Tvde1
May 26 at 11:47












12 Answers
12






active

oldest

votes


















11














It is much cleaner to use iter with 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]


Output:



['Python', 'is', 'an', 'programming', 'language']





share|improve this answer






























    3














    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)





    share|improve this answer






























      3














      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)





      share|improve this answer






























        3














        In the future, an alternative approach will be to use an assignment expression (new in Python 3.8):



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

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





        share|improve this answer






























          2














          You can use itertools.accumulate to get the positions where you want to split the string:



          >>> s = 'Pythonisanprogramminglanguage'
          >>> arr = ['lkjhgf', 'zx', 'qw', 'ertyuiopakk', 'foacdhlc']
          >>> import itertools
          >>> L = list(itertools.accumulate(map(len, arr)))
          >>> L
          [6, 8, 10, 21, 29]


          Now if you zip the list with itself, you get the intervals:



          >>> list(zip([0]+L, L))
          [(0, 6), (6, 8), (8, 10), (10, 21), (21, 29)]


          And you just have to use the intervals to split the string:



          >>> [s[i:j] for i,j in zip([0]+L, L)]
          ['Python', 'is', 'an', 'programming', 'language']





          share|improve this answer






























            1














            Create a simple loop and use the length of the words as your index:



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

            ctr = 0
            words = []
            for x in arr:
            words.append(s[ctr:len(x) + ctr])
            ctr += len(x)

            print(words)

            # ['Python', 'is', 'an', 'programming', 'language']





            share|improve this answer






























              1














              The itertools module has a function named accumulate() (added in Py 3.2) to help make this relatively easy:



              from itertools import accumulate # added in Py 3.2


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

              cuts = tuple(accumulate(len(item) for item in arr))
              words = [s[i:j] for i, j in zip((0,)+cuts, cuts)]
              print(words) # -> ['Python', 'is', 'an', 'programming', 'language']





              share|improve this answer
































                0














                Here is another approach :



                import numpy as np
                ar = [0]+list(map(len, arr))
                ar = list(np.cumsum(ar))
                output_ = [s[i:ar[ar.index(i)+1]] for i in ar[:-1]]


                Output :



                ['Python', 'is', 'an', 'programming', 'language']





                share|improve this answer






























                  0














                  One more way



                  a,l = 0,[]
                  for i in map(len,arr):
                  l.append(s[a:a+i])
                  a+=i
                  print (l)
                  #['Python', 'is', 'an', 'programming', 'language']





                  share|improve this answer






























                    0














                    Props to the answer using iter. The accumulate answers are my favorite. Here is another accumulate answer using map instead of a list comprehension



                    import itertools

                    s = 'Pythonisanprogramminglanguage'
                    arr = ['lkjhgf', 'zx', 'qw', 'ertyuiopakk', 'foacdhlc']
                    ticks = itertools.accumulate(map(len, arr[0:]))
                    words = list(map(lambda i, x: s[i:len(x) + i], (0,) + tuple(ticks), arr))


                    Output:



                    ['Python', 'is', 'an', 'programming', 'language']





                    share|improve this answer






























                      0














                      You could collect slices off the front of s.



                      output = []

                      for word in arr:
                      i = len(word)
                      chunk, s = s[:i], s[i:]
                      output.append(chunk)

                      print(output) # -> ['Python', 'is', 'an', 'programming', 'language']





                      share|improve this answer






























                        0














                        Yet another approach would be to create a regex pattern describing the desired length of words. You can replace every character by . (=any character) and surround the words with ():



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

                        import re

                        pattern = '(' + ')('.join(re.sub('.', '.', word) for word in arr) + ')'
                        #=> '(......)(..)(.)(...........)(........)'


                        If the pattern matches, you get the desired words in groups directly:



                        s = 'Pythonisaprogramminglanguage'
                        re.match(pattern, s).groups()
                        #=> ('Python', 'is', 'a', 'programming', 'language')





                        share|improve this answer























                          Your Answer






                          StackExchange.ifUsing("editor", function ()
                          StackExchange.using("externalEditor", function ()
                          StackExchange.using("snippets", function ()
                          StackExchange.snippets.init();
                          );
                          );
                          , "code-snippets");

                          StackExchange.ready(function()
                          var channelOptions =
                          tags: "".split(" "),
                          id: "1"
                          ;
                          initTagRenderer("".split(" "), "".split(" "), channelOptions);

                          StackExchange.using("externalEditor", function()
                          // Have to fire editor after snippets, if snippets enabled
                          if (StackExchange.settings.snippets.snippetsEnabled)
                          StackExchange.using("snippets", function()
                          createEditor();
                          );

                          else
                          createEditor();

                          );

                          function createEditor()
                          StackExchange.prepareEditor(
                          heartbeatType: 'answer',
                          autoActivateHeartbeat: false,
                          convertImagesToLinks: true,
                          noModals: true,
                          showLowRepImageUploadWarning: true,
                          reputationToPostImages: 10,
                          bindNavPrevention: true,
                          postfix: "",
                          imageUploader:
                          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                          allowUrls: true
                          ,
                          onDemand: true,
                          discardSelector: ".discard-answer"
                          ,immediatelyShowMarkdownHelp:true
                          );



                          );













                          draft saved

                          draft discarded


















                          StackExchange.ready(
                          function ()
                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56305553%2fadding-spaces-to-string-based-on-list%23new-answer', 'question_page');

                          );

                          Post as a guest















                          Required, but never shown

























                          12 Answers
                          12






                          active

                          oldest

                          votes








                          12 Answers
                          12






                          active

                          oldest

                          votes









                          active

                          oldest

                          votes






                          active

                          oldest

                          votes









                          11














                          It is much cleaner to use iter with 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]


                          Output:



                          ['Python', 'is', 'an', 'programming', 'language']





                          share|improve this answer



























                            11














                            It is much cleaner to use iter with 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]


                            Output:



                            ['Python', 'is', 'an', 'programming', 'language']





                            share|improve this answer

























                              11












                              11








                              11







                              It is much cleaner to use iter with 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]


                              Output:



                              ['Python', 'is', 'an', 'programming', 'language']





                              share|improve this answer













                              It is much cleaner to use iter with 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]


                              Output:



                              ['Python', 'is', 'an', 'programming', 'language']






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered May 25 at 15:10









                              Ajax1234Ajax1234

                              44.8k42958




                              44.8k42958























                                  3














                                  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)





                                  share|improve this answer



























                                    3














                                    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)





                                    share|improve this answer

























                                      3












                                      3








                                      3







                                      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)





                                      share|improve this answer













                                      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)






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered May 25 at 14:08









                                      SimonSimon

                                      2,07753055




                                      2,07753055





















                                          3














                                          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)





                                          share|improve this answer



























                                            3














                                            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)





                                            share|improve this answer

























                                              3












                                              3








                                              3







                                              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)





                                              share|improve this answer













                                              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)






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered May 25 at 14:08









                                              sekkysekky

                                              676612




                                              676612





















                                                  3














                                                  In the future, an alternative approach will be to use an assignment expression (new in Python 3.8):



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

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





                                                  share|improve this answer



























                                                    3














                                                    In the future, an alternative approach will be to use an assignment expression (new in Python 3.8):



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

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





                                                    share|improve this answer

























                                                      3












                                                      3








                                                      3







                                                      In the future, an alternative approach will be to use an assignment expression (new in Python 3.8):



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

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





                                                      share|improve this answer













                                                      In the future, an alternative approach will be to use an assignment expression (new in Python 3.8):



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

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






                                                      share|improve this answer












                                                      share|improve this answer



                                                      share|improve this answer










                                                      answered May 25 at 14:27









                                                      user200783user200783

                                                      6,54495292




                                                      6,54495292





















                                                          2














                                                          You can use itertools.accumulate to get the positions where you want to split the string:



                                                          >>> s = 'Pythonisanprogramminglanguage'
                                                          >>> arr = ['lkjhgf', 'zx', 'qw', 'ertyuiopakk', 'foacdhlc']
                                                          >>> import itertools
                                                          >>> L = list(itertools.accumulate(map(len, arr)))
                                                          >>> L
                                                          [6, 8, 10, 21, 29]


                                                          Now if you zip the list with itself, you get the intervals:



                                                          >>> list(zip([0]+L, L))
                                                          [(0, 6), (6, 8), (8, 10), (10, 21), (21, 29)]


                                                          And you just have to use the intervals to split the string:



                                                          >>> [s[i:j] for i,j in zip([0]+L, L)]
                                                          ['Python', 'is', 'an', 'programming', 'language']





                                                          share|improve this answer



























                                                            2














                                                            You can use itertools.accumulate to get the positions where you want to split the string:



                                                            >>> s = 'Pythonisanprogramminglanguage'
                                                            >>> arr = ['lkjhgf', 'zx', 'qw', 'ertyuiopakk', 'foacdhlc']
                                                            >>> import itertools
                                                            >>> L = list(itertools.accumulate(map(len, arr)))
                                                            >>> L
                                                            [6, 8, 10, 21, 29]


                                                            Now if you zip the list with itself, you get the intervals:



                                                            >>> list(zip([0]+L, L))
                                                            [(0, 6), (6, 8), (8, 10), (10, 21), (21, 29)]


                                                            And you just have to use the intervals to split the string:



                                                            >>> [s[i:j] for i,j in zip([0]+L, L)]
                                                            ['Python', 'is', 'an', 'programming', 'language']





                                                            share|improve this answer

























                                                              2












                                                              2








                                                              2







                                                              You can use itertools.accumulate to get the positions where you want to split the string:



                                                              >>> s = 'Pythonisanprogramminglanguage'
                                                              >>> arr = ['lkjhgf', 'zx', 'qw', 'ertyuiopakk', 'foacdhlc']
                                                              >>> import itertools
                                                              >>> L = list(itertools.accumulate(map(len, arr)))
                                                              >>> L
                                                              [6, 8, 10, 21, 29]


                                                              Now if you zip the list with itself, you get the intervals:



                                                              >>> list(zip([0]+L, L))
                                                              [(0, 6), (6, 8), (8, 10), (10, 21), (21, 29)]


                                                              And you just have to use the intervals to split the string:



                                                              >>> [s[i:j] for i,j in zip([0]+L, L)]
                                                              ['Python', 'is', 'an', 'programming', 'language']





                                                              share|improve this answer













                                                              You can use itertools.accumulate to get the positions where you want to split the string:



                                                              >>> s = 'Pythonisanprogramminglanguage'
                                                              >>> arr = ['lkjhgf', 'zx', 'qw', 'ertyuiopakk', 'foacdhlc']
                                                              >>> import itertools
                                                              >>> L = list(itertools.accumulate(map(len, arr)))
                                                              >>> L
                                                              [6, 8, 10, 21, 29]


                                                              Now if you zip the list with itself, you get the intervals:



                                                              >>> list(zip([0]+L, L))
                                                              [(0, 6), (6, 8), (8, 10), (10, 21), (21, 29)]


                                                              And you just have to use the intervals to split the string:



                                                              >>> [s[i:j] for i,j in zip([0]+L, L)]
                                                              ['Python', 'is', 'an', 'programming', 'language']






                                                              share|improve this answer












                                                              share|improve this answer



                                                              share|improve this answer










                                                              answered May 25 at 15:53









                                                              jferardjferard

                                                              2,8451416




                                                              2,8451416





















                                                                  1














                                                                  Create a simple loop and use the length of the words as your index:



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

                                                                  ctr = 0
                                                                  words = []
                                                                  for x in arr:
                                                                  words.append(s[ctr:len(x) + ctr])
                                                                  ctr += len(x)

                                                                  print(words)

                                                                  # ['Python', 'is', 'an', 'programming', 'language']





                                                                  share|improve this answer



























                                                                    1














                                                                    Create a simple loop and use the length of the words as your index:



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

                                                                    ctr = 0
                                                                    words = []
                                                                    for x in arr:
                                                                    words.append(s[ctr:len(x) + ctr])
                                                                    ctr += len(x)

                                                                    print(words)

                                                                    # ['Python', 'is', 'an', 'programming', 'language']





                                                                    share|improve this answer

























                                                                      1












                                                                      1








                                                                      1







                                                                      Create a simple loop and use the length of the words as your index:



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

                                                                      ctr = 0
                                                                      words = []
                                                                      for x in arr:
                                                                      words.append(s[ctr:len(x) + ctr])
                                                                      ctr += len(x)

                                                                      print(words)

                                                                      # ['Python', 'is', 'an', 'programming', 'language']





                                                                      share|improve this answer













                                                                      Create a simple loop and use the length of the words as your index:



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

                                                                      ctr = 0
                                                                      words = []
                                                                      for x in arr:
                                                                      words.append(s[ctr:len(x) + ctr])
                                                                      ctr += len(x)

                                                                      print(words)

                                                                      # ['Python', 'is', 'an', 'programming', 'language']






                                                                      share|improve this answer












                                                                      share|improve this answer



                                                                      share|improve this answer










                                                                      answered May 25 at 14:10









                                                                      AK47AK47

                                                                      5,10821940




                                                                      5,10821940





















                                                                          1














                                                                          The itertools module has a function named accumulate() (added in Py 3.2) to help make this relatively easy:



                                                                          from itertools import accumulate # added in Py 3.2


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

                                                                          cuts = tuple(accumulate(len(item) for item in arr))
                                                                          words = [s[i:j] for i, j in zip((0,)+cuts, cuts)]
                                                                          print(words) # -> ['Python', 'is', 'an', 'programming', 'language']





                                                                          share|improve this answer





























                                                                            1














                                                                            The itertools module has a function named accumulate() (added in Py 3.2) to help make this relatively easy:



                                                                            from itertools import accumulate # added in Py 3.2


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

                                                                            cuts = tuple(accumulate(len(item) for item in arr))
                                                                            words = [s[i:j] for i, j in zip((0,)+cuts, cuts)]
                                                                            print(words) # -> ['Python', 'is', 'an', 'programming', 'language']





                                                                            share|improve this answer



























                                                                              1












                                                                              1








                                                                              1







                                                                              The itertools module has a function named accumulate() (added in Py 3.2) to help make this relatively easy:



                                                                              from itertools import accumulate # added in Py 3.2


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

                                                                              cuts = tuple(accumulate(len(item) for item in arr))
                                                                              words = [s[i:j] for i, j in zip((0,)+cuts, cuts)]
                                                                              print(words) # -> ['Python', 'is', 'an', 'programming', 'language']





                                                                              share|improve this answer















                                                                              The itertools module has a function named accumulate() (added in Py 3.2) to help make this relatively easy:



                                                                              from itertools import accumulate # added in Py 3.2


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

                                                                              cuts = tuple(accumulate(len(item) for item in arr))
                                                                              words = [s[i:j] for i, j in zip((0,)+cuts, cuts)]
                                                                              print(words) # -> ['Python', 'is', 'an', 'programming', 'language']






                                                                              share|improve this answer














                                                                              share|improve this answer



                                                                              share|improve this answer








                                                                              edited May 25 at 18:20









                                                                              wjandrea

                                                                              2,1331333




                                                                              2,1331333










                                                                              answered May 25 at 17:06









                                                                              martineaumartineau

                                                                              72.5k1094191




                                                                              72.5k1094191





















                                                                                  0














                                                                                  Here is another approach :



                                                                                  import numpy as np
                                                                                  ar = [0]+list(map(len, arr))
                                                                                  ar = list(np.cumsum(ar))
                                                                                  output_ = [s[i:ar[ar.index(i)+1]] for i in ar[:-1]]


                                                                                  Output :



                                                                                  ['Python', 'is', 'an', 'programming', 'language']





                                                                                  share|improve this answer



























                                                                                    0














                                                                                    Here is another approach :



                                                                                    import numpy as np
                                                                                    ar = [0]+list(map(len, arr))
                                                                                    ar = list(np.cumsum(ar))
                                                                                    output_ = [s[i:ar[ar.index(i)+1]] for i in ar[:-1]]


                                                                                    Output :



                                                                                    ['Python', 'is', 'an', 'programming', 'language']





                                                                                    share|improve this answer

























                                                                                      0












                                                                                      0








                                                                                      0







                                                                                      Here is another approach :



                                                                                      import numpy as np
                                                                                      ar = [0]+list(map(len, arr))
                                                                                      ar = list(np.cumsum(ar))
                                                                                      output_ = [s[i:ar[ar.index(i)+1]] for i in ar[:-1]]


                                                                                      Output :



                                                                                      ['Python', 'is', 'an', 'programming', 'language']





                                                                                      share|improve this answer













                                                                                      Here is another approach :



                                                                                      import numpy as np
                                                                                      ar = [0]+list(map(len, arr))
                                                                                      ar = list(np.cumsum(ar))
                                                                                      output_ = [s[i:ar[ar.index(i)+1]] for i in ar[:-1]]


                                                                                      Output :



                                                                                      ['Python', 'is', 'an', 'programming', 'language']






                                                                                      share|improve this answer












                                                                                      share|improve this answer



                                                                                      share|improve this answer










                                                                                      answered May 25 at 14:29









                                                                                      Arkistarvh KltzuonstevArkistarvh Kltzuonstev

                                                                                      2,89911231




                                                                                      2,89911231





















                                                                                          0














                                                                                          One more way



                                                                                          a,l = 0,[]
                                                                                          for i in map(len,arr):
                                                                                          l.append(s[a:a+i])
                                                                                          a+=i
                                                                                          print (l)
                                                                                          #['Python', 'is', 'an', 'programming', 'language']





                                                                                          share|improve this answer



























                                                                                            0














                                                                                            One more way



                                                                                            a,l = 0,[]
                                                                                            for i in map(len,arr):
                                                                                            l.append(s[a:a+i])
                                                                                            a+=i
                                                                                            print (l)
                                                                                            #['Python', 'is', 'an', 'programming', 'language']





                                                                                            share|improve this answer

























                                                                                              0












                                                                                              0








                                                                                              0







                                                                                              One more way



                                                                                              a,l = 0,[]
                                                                                              for i in map(len,arr):
                                                                                              l.append(s[a:a+i])
                                                                                              a+=i
                                                                                              print (l)
                                                                                              #['Python', 'is', 'an', 'programming', 'language']





                                                                                              share|improve this answer













                                                                                              One more way



                                                                                              a,l = 0,[]
                                                                                              for i in map(len,arr):
                                                                                              l.append(s[a:a+i])
                                                                                              a+=i
                                                                                              print (l)
                                                                                              #['Python', 'is', 'an', 'programming', 'language']






                                                                                              share|improve this answer












                                                                                              share|improve this answer



                                                                                              share|improve this answer










                                                                                              answered May 25 at 14:36









                                                                                              TranshumanTranshuman

                                                                                              2,9761412




                                                                                              2,9761412





















                                                                                                  0














                                                                                                  Props to the answer using iter. The accumulate answers are my favorite. Here is another accumulate answer using map instead of a list comprehension



                                                                                                  import itertools

                                                                                                  s = 'Pythonisanprogramminglanguage'
                                                                                                  arr = ['lkjhgf', 'zx', 'qw', 'ertyuiopakk', 'foacdhlc']
                                                                                                  ticks = itertools.accumulate(map(len, arr[0:]))
                                                                                                  words = list(map(lambda i, x: s[i:len(x) + i], (0,) + tuple(ticks), arr))


                                                                                                  Output:



                                                                                                  ['Python', 'is', 'an', 'programming', 'language']





                                                                                                  share|improve this answer



























                                                                                                    0














                                                                                                    Props to the answer using iter. The accumulate answers are my favorite. Here is another accumulate answer using map instead of a list comprehension



                                                                                                    import itertools

                                                                                                    s = 'Pythonisanprogramminglanguage'
                                                                                                    arr = ['lkjhgf', 'zx', 'qw', 'ertyuiopakk', 'foacdhlc']
                                                                                                    ticks = itertools.accumulate(map(len, arr[0:]))
                                                                                                    words = list(map(lambda i, x: s[i:len(x) + i], (0,) + tuple(ticks), arr))


                                                                                                    Output:



                                                                                                    ['Python', 'is', 'an', 'programming', 'language']





                                                                                                    share|improve this answer

























                                                                                                      0












                                                                                                      0








                                                                                                      0







                                                                                                      Props to the answer using iter. The accumulate answers are my favorite. Here is another accumulate answer using map instead of a list comprehension



                                                                                                      import itertools

                                                                                                      s = 'Pythonisanprogramminglanguage'
                                                                                                      arr = ['lkjhgf', 'zx', 'qw', 'ertyuiopakk', 'foacdhlc']
                                                                                                      ticks = itertools.accumulate(map(len, arr[0:]))
                                                                                                      words = list(map(lambda i, x: s[i:len(x) + i], (0,) + tuple(ticks), arr))


                                                                                                      Output:



                                                                                                      ['Python', 'is', 'an', 'programming', 'language']





                                                                                                      share|improve this answer













                                                                                                      Props to the answer using iter. The accumulate answers are my favorite. Here is another accumulate answer using map instead of a list comprehension



                                                                                                      import itertools

                                                                                                      s = 'Pythonisanprogramminglanguage'
                                                                                                      arr = ['lkjhgf', 'zx', 'qw', 'ertyuiopakk', 'foacdhlc']
                                                                                                      ticks = itertools.accumulate(map(len, arr[0:]))
                                                                                                      words = list(map(lambda i, x: s[i:len(x) + i], (0,) + tuple(ticks), arr))


                                                                                                      Output:



                                                                                                      ['Python', 'is', 'an', 'programming', 'language']






                                                                                                      share|improve this answer












                                                                                                      share|improve this answer



                                                                                                      share|improve this answer










                                                                                                      answered May 25 at 17:24









                                                                                                      Buckeye14GuyBuckeye14Guy

                                                                                                      1096




                                                                                                      1096





















                                                                                                          0














                                                                                                          You could collect slices off the front of s.



                                                                                                          output = []

                                                                                                          for word in arr:
                                                                                                          i = len(word)
                                                                                                          chunk, s = s[:i], s[i:]
                                                                                                          output.append(chunk)

                                                                                                          print(output) # -> ['Python', 'is', 'an', 'programming', 'language']





                                                                                                          share|improve this answer



























                                                                                                            0














                                                                                                            You could collect slices off the front of s.



                                                                                                            output = []

                                                                                                            for word in arr:
                                                                                                            i = len(word)
                                                                                                            chunk, s = s[:i], s[i:]
                                                                                                            output.append(chunk)

                                                                                                            print(output) # -> ['Python', 'is', 'an', 'programming', 'language']





                                                                                                            share|improve this answer

























                                                                                                              0












                                                                                                              0








                                                                                                              0







                                                                                                              You could collect slices off the front of s.



                                                                                                              output = []

                                                                                                              for word in arr:
                                                                                                              i = len(word)
                                                                                                              chunk, s = s[:i], s[i:]
                                                                                                              output.append(chunk)

                                                                                                              print(output) # -> ['Python', 'is', 'an', 'programming', 'language']





                                                                                                              share|improve this answer













                                                                                                              You could collect slices off the front of s.



                                                                                                              output = []

                                                                                                              for word in arr:
                                                                                                              i = len(word)
                                                                                                              chunk, s = s[:i], s[i:]
                                                                                                              output.append(chunk)

                                                                                                              print(output) # -> ['Python', 'is', 'an', 'programming', 'language']






                                                                                                              share|improve this answer












                                                                                                              share|improve this answer



                                                                                                              share|improve this answer










                                                                                                              answered May 25 at 18:05









                                                                                                              wjandreawjandrea

                                                                                                              2,1331333




                                                                                                              2,1331333





















                                                                                                                  0














                                                                                                                  Yet another approach would be to create a regex pattern describing the desired length of words. You can replace every character by . (=any character) and surround the words with ():



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

                                                                                                                  import re

                                                                                                                  pattern = '(' + ')('.join(re.sub('.', '.', word) for word in arr) + ')'
                                                                                                                  #=> '(......)(..)(.)(...........)(........)'


                                                                                                                  If the pattern matches, you get the desired words in groups directly:



                                                                                                                  s = 'Pythonisaprogramminglanguage'
                                                                                                                  re.match(pattern, s).groups()
                                                                                                                  #=> ('Python', 'is', 'a', 'programming', 'language')





                                                                                                                  share|improve this answer



























                                                                                                                    0














                                                                                                                    Yet another approach would be to create a regex pattern describing the desired length of words. You can replace every character by . (=any character) and surround the words with ():



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

                                                                                                                    import re

                                                                                                                    pattern = '(' + ')('.join(re.sub('.', '.', word) for word in arr) + ')'
                                                                                                                    #=> '(......)(..)(.)(...........)(........)'


                                                                                                                    If the pattern matches, you get the desired words in groups directly:



                                                                                                                    s = 'Pythonisaprogramminglanguage'
                                                                                                                    re.match(pattern, s).groups()
                                                                                                                    #=> ('Python', 'is', 'a', 'programming', 'language')





                                                                                                                    share|improve this answer

























                                                                                                                      0












                                                                                                                      0








                                                                                                                      0







                                                                                                                      Yet another approach would be to create a regex pattern describing the desired length of words. You can replace every character by . (=any character) and surround the words with ():



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

                                                                                                                      import re

                                                                                                                      pattern = '(' + ')('.join(re.sub('.', '.', word) for word in arr) + ')'
                                                                                                                      #=> '(......)(..)(.)(...........)(........)'


                                                                                                                      If the pattern matches, you get the desired words in groups directly:



                                                                                                                      s = 'Pythonisaprogramminglanguage'
                                                                                                                      re.match(pattern, s).groups()
                                                                                                                      #=> ('Python', 'is', 'a', 'programming', 'language')





                                                                                                                      share|improve this answer













                                                                                                                      Yet another approach would be to create a regex pattern describing the desired length of words. You can replace every character by . (=any character) and surround the words with ():



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

                                                                                                                      import re

                                                                                                                      pattern = '(' + ')('.join(re.sub('.', '.', word) for word in arr) + ')'
                                                                                                                      #=> '(......)(..)(.)(...........)(........)'


                                                                                                                      If the pattern matches, you get the desired words in groups directly:



                                                                                                                      s = 'Pythonisaprogramminglanguage'
                                                                                                                      re.match(pattern, s).groups()
                                                                                                                      #=> ('Python', 'is', 'a', 'programming', 'language')






                                                                                                                      share|improve this answer












                                                                                                                      share|improve this answer



                                                                                                                      share|improve this answer










                                                                                                                      answered May 26 at 7:57









                                                                                                                      Eric DuminilEric Duminil

                                                                                                                      42.1k73777




                                                                                                                      42.1k73777



























                                                                                                                          draft saved

                                                                                                                          draft discarded
















































                                                                                                                          Thanks for contributing an answer to Stack Overflow!


                                                                                                                          • Please be sure to answer the question. Provide details and share your research!

                                                                                                                          But avoid


                                                                                                                          • Asking for help, clarification, or responding to other answers.

                                                                                                                          • Making statements based on opinion; back them up with references or personal experience.

                                                                                                                          To learn more, see our tips on writing great answers.




                                                                                                                          draft saved


                                                                                                                          draft discarded














                                                                                                                          StackExchange.ready(
                                                                                                                          function ()
                                                                                                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56305553%2fadding-spaces-to-string-based-on-list%23new-answer', 'question_page');

                                                                                                                          );

                                                                                                                          Post as a guest















                                                                                                                          Required, but never shown





















































                                                                                                                          Required, but never shown














                                                                                                                          Required, but never shown












                                                                                                                          Required, but never shown







                                                                                                                          Required, but never shown

































                                                                                                                          Required, but never shown














                                                                                                                          Required, but never shown












                                                                                                                          Required, but never shown







                                                                                                                          Required, but never shown







                                                                                                                          Popular posts from this blog

                                                                                                                          Wikipedia:Vital articles Мазмуну Biography - Өмүр баян Philosophy and psychology - Философия жана психология Religion - Дин Social sciences - Коомдук илимдер Language and literature - Тил жана адабият Science - Илим Technology - Технология Arts and recreation - Искусство жана эс алуу History and geography - Тарых жана география Навигация менюсу

                                                                                                                          Bruxelas-Capital Índice Historia | Composición | Situación lingüística | Clima | Cidades irmandadas | Notas | Véxase tamén | Menú de navegacióneO uso das linguas en Bruxelas e a situación do neerlandés"Rexión de Bruxelas Capital"o orixinalSitio da rexiónPáxina de Bruselas no sitio da Oficina de Promoción Turística de Valonia e BruxelasMapa Interactivo da Rexión de Bruxelas-CapitaleeWorldCat332144929079854441105155190212ID28008674080552-90000 0001 0666 3698n94104302ID540940339365017018237

                                                                                                                          What should I write in an apology letter, since I have decided not to join a company after accepting an offer letterShould I keep looking after accepting a job offer?What should I do when I've been verbally told I would get an offer letter, but still haven't gotten one after 4 weeks?Do I accept an offer from a company that I am not likely to join?New job hasn't confirmed starting date and I want to give current employer as much notice as possibleHow should I address my manager in my resignation letter?HR delayed background verification, now jobless as resignedNo email communication after accepting a formal written offer. How should I phrase the call?What should I do if after receiving a verbal offer letter I am informed that my written job offer is put on hold due to some internal issues?Should I inform the current employer that I am about to resign within 1-2 weeks since I have signed the offer letter and waiting for visa?What company will do, if I send their offer letter to another company