omz:forum

    • Register
    • Login
    • Search
    • Recent
    • Popular

    Welcome!

    This is the community forum for my apps Pythonista and Editorial.

    For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.


    How do you split/slice list of strings

    Pythonista
    3
    4
    1760
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • sodoku
      sodoku last edited by sodoku

      I have a question about a list of strings

      Say I got a list like

      a=[‘Haloween’, ‘Boom’, ‘hi’, ‘Howl’, ‘if’, ‘ghosts’]
      

      How do you split or slice the strings to make a list like

      a=[‘Ha’, ‘lo’, ‘we’, ‘en’, ‘Bo’, ‘om’, ‘hi’, ‘Ho’, ‘wl’, ‘if’, ‘gh’, ‘os’, ‘ts’]
      

      Is this possible to do?

      1 Reply Last reply Reply Quote 0
      • bennr01
        bennr01 last edited by

        [s[i:i+2] for s in a for i in range(0, len(s), 2)]

        Replace 2 with chunk length.

        1 Reply Last reply Reply Quote 0
        • sodoku
          sodoku last edited by

          Cool awesome Thanks this worked I did not know you could use for twice in one line of code

          a=[‘Haloween’, ‘Boom’, ‘hi’, ‘Howl’, ‘if’, ‘ghosts’]
          B=[s[i:i+2] for s in a for i in range(0, len(s), 2)]
          Print(B)
          
          1 Reply Last reply Reply Quote 0
          • ccc
            ccc last edited by

            The reversed pop pop solution...

            def two_chars(a):
                s = list(reversed("".join(a)))
                while s:
                    yield "".join((s.pop(), s.pop()))
            
            print(list(two_chars(a)))
            
            1 Reply Last reply Reply Quote 0
            • First post
              Last post
            Powered by NodeBB Forums | Contributors