I am trying to run pytest to test my function but I am running into an issue where I am trying to split a function called get_prepositional_phrase(amount) that returns a string of three variables into each variable but after I split it I keep getting a list index out of range error
my code for the string I am trying to split is:
phrase = (f'{connect} {determiner2} {noun2}')
my code is below for the test function.
def test_get_prepositional_phrase():
phrase1 = get_prepositional_phrase(1)
prep = ["about", "above", "across", "after", "along",
"around", "at", "before", "behind", "below",
"beyond", "by", "despite", "except", "for",
"from", "in", "into", "near", "of",
"off", "on", "onto", "out", "over",
"past", "to", "under", "with", "without"]
for word in phrase1:
parts = word.split()
one = parts[0]
# two = parts[1]
# three = parts[2]
for _ in range(30):
connector = get_preposition()
assert one in connector
CodePudding user response:
Line 115 will raise an exception if the parts
list has only one (or zero) items in it. Given your code is
one = parts[1]
# two = parts[1]
# three = parts[2]
I would say that you should be assigning parts[0]
, rather than parts[1]
, to one
. Additionally, a good rule to follow is to check all required pre-conditions first. That would involve:
assert type(phrase1) is list # Is list.
assert len(phrase1) >= 2 # Minimum size.
assert(all([type(x) is str for x in phrase1])) # All items are string.
for word in phrase1:
pass # Guaranteed safe to use word[1] as a string here.
In any case, the fact that your phrase is constructed as:
f'{connect} {determiner2} {noun2}'
means that it is a single string rather than a list of words. That means that:
for word in phrase1: # One character at a time.
parts = word.split() # One-element list with that character.
one = parts[1] # NO !
will always give you a single-character string in word and therefore parts
will always be a one-element list containing that one-character string. Hence the parts[1]
expression will fail.
What you need instead is the following:
for word in phrase1.split(): # One word at a time.
one = word[0]
# two = word[1]
# three = word[2]
Bottom line: for i in a_string
gives you each character of the string while for i in a_list_of_strings
gives you each string in the list.