-1

Is there a way to extract a word using the spaces around it like so:

string = 'what does blah mean?'

With prior knowledge of only there being "what does" and then the word and then "mean", how would one get the word?

Michael Armes
  • 1,056
  • 2
  • 17
  • 31
Void
  • 23
  • 2

2 Answers2

1

The easy way is to use a regular expression such as:

import re

test = re.compile(r"what does (.*?) mean", re.IGNORE_CASE)

then find all in your input and use the [1] element from each match.

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
1

As says https://docs.python.org/2/library/string.html#string.split:

string.split(s[, sep[, maxsplit]])

Return a list of the words of the string s. If the optional second argument sep is absent or None, the words are separated by arbitrary strings of whitespace characters (space, tab, newline, return, formfeed). If the second argument sep is present and not None, it specifies a string to be used as the word separator. The returned list will then have one more item than the number of non-overlapping occurrences of the separator in the string. If maxsplit is given, at most maxsplit number of splits occur, and the remainder of the string is returned as the final element of the list (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

The behavior of split on an empty string depends on the value of sep. If sep is not specified, or specified as None, the result will be an empty list. If sep is specified as any string, the result will be a list containing one element which is an empty string.

So, you would use string.split()[the_word_you_want-1].

Douglas
  • 1,304
  • 10
  • 26