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

家住魔仙堡 提交于 2019-12-17 10:45:01

问题


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?


回答1:


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

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



回答2:


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."




回答3:


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

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



回答4:


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



回答5:


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("<>")



回答6:


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



回答7:


Without regex

intro.split('<>',1)[1]


来源:https://stackoverflow.com/questions/30945784/how-to-remove-all-characters-before-a-specific-character-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!