How to split a string and keep the delimiter

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mquinta
    New Member
    • Feb 2011
    • 4

    How to split a string and keep the delimiter

    Hi!
    So I have a string that I want to split but I need to keep the exact part that I'm splitting

    for example
    Code:
    s_words = 'i need toKeepTHISword'
    
    splitWord = s_words.split('THIS')
    
    # Result: ['i need toKeep', 'word']

    Result wanted:

    ['THIS']




    Thanks in advance!
    Last edited by bvdet; Feb 23 '11, 08:07 PM. Reason: Improve title
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Use string method index() and slicing.
    Code:
    >>> idx = 'i need toKeepTHISword'.index("THIS")
    >>> 'i need toKeepTHISword'[idx:idx+len("THIS")]
    'THIS'
    >>>

    Comment

    • Rabbit
      Recognized Expert MVP
      • Jan 2007
      • 12517

      #3
      Or just append THIS to every item except the last item. Since it must necessarily end with the delimiter.

      Comment

      • mquinta
        New Member
        • Feb 2011
        • 4

        #4
        Thank you both!
        I'll take a more careful look to the index() method, but with that lines the script works just fine :)

        Comment

        Working...