繁体   English   中英

如果多次出现该字符,则将字符串的一部分剥离到特定字符之前

[英]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()怎么样?

str = 'Mark: I am sending the file: abc.txt'
print(str.split(':', 1)[-1])

如果分隔符不在初始字符串中,请使用-1来说明列表索引超出范围

输出:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM