In practice, I had to change this: if len(query) > 0 and query[-1] == query[-1].capitalize(): group = query.pop() to this: if len(query) > 0 and query[-1][0] == query[-1].capitalize()[0]: group = query.pop() This is because I only wanted to test the case of the first letter of the string.