-1

here's the String variable

question = "i need to know about something..."

how do i get the words after "i need to know about", if sometimes the question variable changes become something like this:

question = " i need to know about something..." 

or

question = "hmmm.... i need to know about something"

i mean, no matter where index is, but i need to know what the random word come after this sentence -> "i need to know about", in this case the result will be "something..."

Ajax1234
  • 58,711
  • 7
  • 46
  • 83
허민선
  • 57
  • 1
  • 7

5 Answers5

1

A quick and dirty solution would be to use str.strip(). It's quick and dirty because it's case insensitive and will only work if the exact string is present

In [22]: "i need to know about something...".split("i need to know about")
Out[22]: ['', ' something...']

In [23]: "hmmm.... i need to know about something".split("i need to know about")
Out[23]: ['hmmm.... ', ' something']

In [24]: "hmmm.... i need to know about  something".split("i need to know about")
Out[24]: ['hmmm.... ', '  something']

In [25]: "hmmm.... i need to know  about something".split("i need to know about")
Out[25]: ['hmmm.... i need to know  about something']

The last case won't work as the strings don't match exactly (note the 2 spaces between know and about.

A regular expression as some of the other answers suggest will be much more comprehensive

aydow
  • 3,081
  • 1
  • 18
  • 33
0

You can try this:

question = "hmmm.... i need to know about something"

new_data = question[question.index("i need to know about")+len("i need to know about"):]

Output:

something

Using regex:

import re

data = re.findall("(?<=i need to know about)\s[a-zA-Z\s]+", question)

print(data)

Output:

[' something']
Ajax1234
  • 58,711
  • 7
  • 46
  • 83
0

If it's a string then you could just get the index of the string you're looking for and get everything after that, like so:

start = question.index('i need to know about')
finish = start + len('i need to know about')
print(question[finish:]) # something...
jake2389
  • 1,176
  • 7
  • 19
0

You could use Regular expressions.

import re
s = "hmmm.... i need to know about something"
regexp = re.compile("i need to know about(.*)$")
print(regexp.search(s).group(1))

Outputs:

 something

If you want to clean the output, you can always .strip()

print(regexp.search(s).group(1).strip())

Outputs:

something
David Metcalfe
  • 1,753
  • 21
  • 36
0

You can use regex to extract the content after "i need to know about".

import re

pattern = ".*?i need to know about (.*)"

content = re.search(pattern, sentence).group(1)
stamaimer
  • 5,169
  • 4
  • 26
  • 48