Search code examples
pythonstringpython-3.xstrip

Python 3 String Method?


Is there anyway to strip or replace or anything like that from one index to another index within a single string?

For example, if I have a string like "first - second - third" and I want to remove the middle part (" - second - "), how could I do this?

Thanks in advance.


Solution

  • Your string:

    s = 'first - second - third'
    

    and the possible solutions:

    s.replace(' - second - ', '')
    

    or

    ''.join(s.split(' - ')[::2])
    

    or

    ''.join(s.split(' - second - '))
    

    or if you know the indices:

    s[:5] + s[-5:]
    

    or just searching for the first and last space:

    s[:s.index(' ')] + s[s.rindex(' ')+1:]
    

    all of them return 'firstthird'