[英]Strip part of string before a particular character, in a case where the character occurs multiple times
我需要将字符串从字符':'
之前出现的部分剥离掉,其中':'
可能出现多次。 例如:
input: 'Mark: I am sending the file: abc.txt'
output: 'I am sending the file: abc.txt'
我拥有的功能是这个(Python代码)
def process_str(in_str):
str_list = in_str.split(':')[1:]
out_str = ''
for each in str_list:
out_str += each
return out_str
我得到的输出是'I am sending the file abc.txt'
而没有第二个':'
。 有没有办法纠正这个问题? 还可以使此代码在时间和空间复杂度上更有效吗?
split
不是最好的方法。 您要使用正则表达式。
import re
def process_str(in_str):
return re.sub('^.*?: ', '', in_str)
这将返回不带任何内容的字符串,直到第一个:
:(冒号后跟空格)。 您可以在此处阅读有关Python正则表达式的更多信息。
您想要的是out_str = ':'.join(in_str.split(':')[1:])
:由于剥离了所有':'
,因此需要重新插入它们。
更好的方法可能是使用out_str = in_str[in_str.find(':')+1:]
。 find(':')
为您提供第一个':'
的索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.