如何删除Python中特定字符之前的所有字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30945784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:12:23  来源:igfitidea点击:

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

pythonstringreplace

提问by Saroekin

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?

现在我想删除<>之前I'm(或更具体地说,I)。有什么建议?

采纳答案by Avinash Raj

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

使用re.sub. 只需匹配所有字符,I然后将匹配的字符替换为I.

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

回答by Ashkay

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

由于index(char)让您获得字符的第一个索引,您可以简单地执行string[index(char):].

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

例如,在这种情况下index("I") = 2,和intro[2:] = "I'm Tom."

回答by ahmad valipour

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

回答by Brent Washburne

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:

如果您知道要删除的字符,而不是知道从哪里开始,那么您可以使用lstrip()函数:

intro = intro.lstrip("<>")

回答by Satheesh Alathiyur

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

回答by duan

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

str.find可以找到的字符索引certain string's first appearance

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

回答by Mafematic

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)