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

问题描述 投票:0回答:12

我想删除指定字符或字符集之前的所有字符(例如):

intro = "<>I'm Tom."

现在我想删除

<>
之前的
I'm
(或更具体地说,
I
)。有什么建议吗?

python string replace
12个回答
72
投票

使用

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

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

50
投票

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

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

32
投票

由于

index(char)
为您提供了角色的第一个索引,因此您可以简单地执行
string[index(char):]

例如,在本例中

index("I") = 2
intro[2:] = "I'm Tom."


8
投票

如果你知道从哪里开始删除的字符位置,你可以使用切片表示法:

intro = intro[2:]

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

intro = intro.lstrip("<>")

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

2
投票

我循环遍历字符串并传递索引。

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)

2
投票
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())

2
投票
>>> 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."

1
投票

基于@AvinashRaj 答案,您可以使用 re.sub 通过正则表达式用字符串或字符替换子字符串:

import re

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

0
投票

如果字符不在字符串中,则此解决方案有效,但使用 if 语句可能会很慢。

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

0
投票

在看到要停在的字符之前,您可以对所有字符使用

itertools.dropwhile
。然后,您可以使用
''.join()
将生成的可迭代对象转回字符串:

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

输出:

I'm Tom.

-3
投票
import re
intro = "<>I'm Tom."
re.sub(r'<>I', 'I', intro)
© www.soinside.com 2019 - 2024. All rights reserved.