2

I don't know how to do something like this in python:

I have a string s = 'windows 95 is not a windows nt operating system', and I want to get string that contains 'nt' and a number of nearby letters, including spaces.

Expected output for 7 nearby letters:

'indows nt operat'

If it is impossible, then is it possible to get the index of a string I want to find like this:

>>> s = 'windows xp horray'
>>> stringtofind = 'hor'

Expected output:

11, 12, 13

Where I only want to get 11 because it is the start."

Is this possible?

Dilettant
  • 3,267
  • 3
  • 29
  • 29

3 Answers3

2

Use str.find with slicing.

Ex:

s = 'windows 95 is not a windows nt operating system'
to_find = 'nt'
print(s[s.find(to_find)-7:s.find(to_find)+ 7]) 
# --> indows nt oper
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0
position = S.index("nt")
S.[position-7:position+7]
Magellan88
  • 2,543
  • 3
  • 24
  • 36
0

I would suggest using find() to get the index of the substring in the main string and then get the part that you want:

s = 'windows 95 is not a windows nt operating system'
substr = 'nt'
index = s.find(substr)
result = s[index-7: index+len(substr)+7]
print(result)
jsgalarraga
  • 425
  • 6
  • 13