Extracting a substring from a string and also including 10 characters before and after

StackOverflow https://stackoverflow.com/questions/23687213

  •  23-07-2023
  •  | 
  •  

I have a string:

str = "alskdfj asldfj 1234_important_what_i_need_123 sdlfja faslkdjfsdkf 234234_important_what_i_need_12312 alsdfj asdfj"

I want to extract each occurrence of the "%important_what_i_need%" bit from the string, including 10 or so characters before and after the search term.

How do I do this with python? Do I need to import re?

有帮助吗?

解决方案

Starting with "aaafoobbb" and looking for "foo" and the surrounding two characters on either side, you could do:

>>> start_string = "aaafoobbb"
>>> search_string = "foo"
>>> index = start_string.index(search_string)
>>> s[(index - 2) : (index + len(search_string) + 2)]

Should be easy enough to adapt to your needs, although you'll need to add some extra checks to make sure your slice indices are within range (e.g. make sure that index - 2 is not less than 0). You definitely want to become more familiar with slicing and strings in Python.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top