Shubhankar_Goswami
Shubhankar_Goswami

Reputation: 25

Strip part of string before a particular character, in a case where the character occurs multiple times

I need to strip the string off the part that occurs before the character ':', where ':' may occur multiple times. For Example:

input: 'Mark: I am sending the file: abc.txt'
output: 'I am sending the file: abc.txt'

The function I have is this (Python code)

def process_str(in_str):
    str_list = in_str.split(':')[1:]
    out_str = ''
    for each in str_list:
        out_str += each
    return out_str

The output I am getting is 'I am sending the file abc.txt' without the second ':'. Is there a way to correct this? Also can this code be made more efficient in time and space complexity?

Upvotes: 2

Views: 10824

Answers (3)

Sash Sinha
Sash Sinha

Reputation: 22370

How about using split()?

str = 'Mark: I am sending the file: abc.txt'
print(str.split(':', 1)[-1])

Use -1 to account for list index out of bounds if the delimiter is not in the initial string

Output:

I am sending the file: abc.txt'

Try it out here.

Upvotes: 6

Jim Stewart
Jim Stewart

Reputation: 17323

split isn't the best approach for this. You want to use a regular expression.

import re

def process_str(in_str):
  return re.sub('^.*?: ', '', in_str)

This returns the string without anything up to the first : (colon followed by space). You can read more about Python regular expressions here.

Upvotes: 3

Julien
Julien

Reputation: 15071

What you want is out_str = ':'.join(in_str.split(':')[1:]): since you stripped all ':', you need to re-insert them.

A better way would probably to use out_str = in_str[in_str.find(':')+1:]. find(':') gives you the index of the first ':'.

Upvotes: 1

Related Questions