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

                                                                                                                          Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

                                                                                                                          Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

                                                                                                                          Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020