获取子字符串周围的字符半径

2024-04-26 14:29:34 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,如何在子字符串周围获得一定数量的字符

例如,下面是我的字符串:

string='Mad Max: Fury Road'

假设我想在'ax: Fur'的两边添加四个字符到输出中,所以应该是'ad Max: Fury Ro'

如果要查找的子字符串是string中的'Fury Road',那么输出将是'ax: Fury Road',并且它将忽略右侧没有要添加的内容


Tags: 字符串内容数量stringroax字符max
2条回答

您还可以使用.split()获取子字符串前后的字符串,然后返回这两个字符串的部分:

def get_sub_and_surrounding(string,sub,length):
    before,after = string.split(sub,1) #limit to only one split
    return before[-length:] + sub + after[:length]

值得注意的是,在这种情况下,如果sub实际上不是子字符串,那么第一行将引发ValueError

但是你可以得到精确的索引,像这样把它分开:

def get_sub_and_surrounding(string,sub,length):
    i_start = string.index(sub) #index of the start of the substring
    i_end = i_start + len(sub) #index of the end of the substring (one after)

    my_start = max(0, i_start -length)
    # ^prevents use of negative indices from counting
    # from the end of the string by accident

    my_end = min(len(string), i_end+length) #this part isn't actually necessary, "a"[:100] just goes to the end of the string

    return string[my_start : my_end]

在这种情况下,如果sub不在字符串中,string.index(sub)将引发ValueError

^{}在这里非常方便:

def get_sub(string, sub, length):
    before, search, after = string.partition(sub)
    if not search:
        raise ValueError("substring not found")
    return before[-length:] + sub + after[:length]

也可以在if语句中返回before,而不是引发ValueError。这将返回不变的字符串。用法:

print(get_sub("Mad Max: Fury Road", "Fury Road", 4))
#ax: Fury Road
print(get_sub("Mad Max: Fury Road", "Fu", 4))
#ax: Fury R

相关问题 更多 >