我想要删除指定字符或一组字符之前的所有字符(例如):
intro = "<>I'm Tom."
现在我想移除 I'm
(更具体地说是I
)前面的<>
。 你有什么建议吗?
使用re.sub
函数。匹配直到I
的所有字符,然后用匹配的字符替换为I
。
re.sub(r'^.*?I', 'I', stri)
re
还比较陌生,我会再深入了解一下;感谢您的回答,谢谢! - SaroekinI
之间切换 re.sub(r'.*?I', 'I', stri)
。但其他答案将无法满足此要求。 - Avinash Rajre
是最好的选择?你有没有一些好的教程/文章来解释re
的基础知识?感谢你的帮助。 - Saroekinimport re
。 - quentstr.find
可以找到某个字符串的首次出现
的字符索引:
intro[intro.find('I'):]
.find
将返回 -1
,而 some_str[-1:]
是“从最后一个字符开始返回所有字符”。 - user3064538intro[intro.find('I')+1:]
。 - Fisal Assubaieye由于index(char)
将为您获取字符的第一个索引,因此您可以简单地使用string[index(char):]
。
例如,在这种情况下,index("I") = 2
,并且intro[2:] = "I'm Tom."
index
仅返回给定字符串的第一个出现。 - Ashkayintro[intro.index('I'):]
该代码的作用是从字符串intro中找到第一个字母'I'的位置,并返回从该位置开始到字符串末尾的子串。 - mattalxndrValueError
。 - user3064538intro = intro[2:]
如果你不知道从何入手,可以使用lstrip()函数,并且知道要删除的字符:
intro = intro.lstrip("<>")
str = "<>I'm Tom."
temp = str.split("I",1)
temp[0]=temp[0].replace("<>","")
str = "I".join(temp)
'I' + intro.split('I', 1)[1]
。 - Avinash RajI
之前的所有内容吗?另外,[1]
代表什么? - Saroekin>>> 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."
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())
我遍历了字符串并传递了索引。
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)
根据@AvinashRaj的答案,您可以使用re.sub通过正则表达式将子字符串替换为字符串或字符:
missing import re
output_str = re.sub(r'^.*?I', 'I', input_str)
你可以使用itertools.dropwhile
来删除在看到某个字符之前的所有字符。然后,你可以使用''.join()
将结果可迭代对象转换回字符串:
from itertools import dropwhile
''.join(dropwhile(lambda x: x not in stop, intro))
这将输出:
I'm Tom.
I
。 - Saroekin