How to remove all characters before a specific character in Python?

PythonStringReplace

Python Problem Overview


I'd like to remove all characters before a designated character or set of characters (for example):

intro = "<>I'm Tom."

Now I'd like to remove the <> before I'm (or more specifically, I). Any suggestions?

Python Solutions


Solution 1 - Python

Use re.sub. Just match all the chars upto I then replace the matched chars with I.

re.sub(r'^.*?I', 'I', stri)

Solution 2 - Python

str.find could find character index of certain string's first appearance:

intro[intro.find('I'):]

Solution 3 - Python

Since index(char) gets you the first index of the character, you can simply do string[index(char):].

For example, in this case index("I") = 2, and intro[2:] = "I'm Tom."

Solution 4 - Python

If you know the character position of where to start deleting, you can use slice notation:

intro = intro[2:]

Instead of knowing where to start, if you know the characters to remove then you could use the lstrip() function:

intro = intro.lstrip("<>")

Solution 5 - Python

str = "<>I'm Tom."
temp = str.split("I",1)
temp[0]=temp[0].replace("<>","")
str = "I".join(temp)

Solution 6 - Python

I looped through the string and passed the index.

intro_list = []

intro = "<>I'm Tom."
for i in range(len(intro)):
    if intro[i] == '<' or intro[i] == '>':
        pass
    else:
        intro_list.append(intro[i])

intro = ''.join(intro_list)
print(intro)

Solution 7 - Python

>>> intro = "<>I'm Tom."
#Just split the string at the special symbol

>>> intro.split("<>")

Output = ['', "I'm Tom."]

>>> new = intro.split("<>")

>>> new[1]
"I'm Tom."

Solution 8 - Python

import re

date_div = "Blah blah\nblah, Updated: Aug. 23, 2012 Blah blah Updated: Feb. 13, 2019"

up_to_word = ":"
rx_to_first = r'^.*?{}'.format(re.escape(up_to_word))
rx_to_last = r'^.*{}'.format(re.escape(up_to_word))

# (Dot.) In the default mode, this matches any character except a newline. 
# If the DOTALL flag has been specified, this matches any character including a newline.

print("Remove all up to the first occurrence of the word including it:")
print(re.sub(rx_to_first, '', date_div, flags=re.DOTALL).strip())

print("Remove all up to the last occurrence of the word including it:")
print(re.sub(rx_to_last, '', date_div, flags=re.DOTALL).strip())

Solution 9 - Python

This solution works if the character is not in the string too, but uses if statements which can be slow.

if 'I' in intro:
  print('I' + intro.split('I')[1])
else:
  print(intro)

Solution 10 - Python

You can use itertools.dropwhile to all the characters before seeing a character to stop at. Then, you can use ''.join() to turn the resulting iterable back into a string:

from itertools import dropwhile
''.join(dropwhile(lambda x: x not in stop, intro))

This outputs:

I'm Tom.

Solution 11 - Python

Based on the @AvinashRaj answer, you can use re.sub to substituate a substring by a string or a character thanks to regex:

missing import re

output_str = re.sub(r'^.*?I', 'I', input_str)

Solution 12 - Python

import re
intro = "<>I'm Tom."
re.sub(r'<>I', 'I', intro)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSaroekinView Question on Stackoverflow
Solution 1 - PythonAvinash RajView Answer on Stackoverflow
Solution 2 - PythonduanView Answer on Stackoverflow
Solution 3 - PythonAshkayView Answer on Stackoverflow
Solution 4 - PythonBrent WashburneView Answer on Stackoverflow
Solution 5 - Pythonahmad valipourView Answer on Stackoverflow
Solution 6 - PythonMafematicView Answer on Stackoverflow
Solution 7 - PythonChethan RajView Answer on Stackoverflow
Solution 8 - PythonRhea ThomasView Answer on Stackoverflow
Solution 9 - PythonCade HargerView Answer on Stackoverflow
Solution 10 - PythonBrokenBenchmarkView Answer on Stackoverflow
Solution 11 - PythonquentView Answer on Stackoverflow
Solution 12 - PythonSatheesh AlathiyurView Answer on Stackoverflow