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]
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]
您还可以使用
.split()
获取子字符串前后的字符串,然后返回这两个字符串的部分:值得注意的是,在这种情况下,如果
sub
实际上不是子字符串,那么第一行将引发ValueError
但是你可以得到精确的索引,像这样把它分开:
在这种情况下,如果sub不在字符串中,
string.index(sub)
将引发ValueError
^{} 在这里非常方便:
也可以在
if
语句中返回before
,而不是引发ValueError
。这将返回不变的字符串。用法:相关问题 更多 >
编程相关推荐