Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 817
Saroekin Avatar asked Jun 19 '15 19:06

Saroekin


People also ask

How do I remove all characters from a string before a specific character in Python?

To remove everything before the first occurrence of the character '-' in a string, pass the character '-' as separator and 1 as the max split value. The split('-', 1) function will split the string into 2 parts, Part 1 should contain all characters before the first occurrence of character '-'.

How do I remove all characters from a string after a specific character?

Use the String. slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str. indexOf('[')); .

How do you cut a string after a specific character in Python?

Use the split() method to cut string after the character in Python.


2 Answers

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

re.sub(r'^.*?I', 'I', stri) 
like image 174
Avinash Raj Avatar answered Sep 21 '22 00:09

Avinash Raj


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

intro[intro.find('I'):] 
like image 30
duan Avatar answered Sep 20 '22 00:09

duan