Reputation: 17552
I'm working on a definition tester (you enter in words, their part of speeches, and synonyms for each, and it tests you on them). Problem I have is with the part that gets the word:
def get_word(): # this is in another function, that's why it is indented
import easygui as eg
word_info = eg.multenterbox(msg = 'Enter in the following information about each word.'
, title = 'Definition Tester'
, fields = ['Word: ', 'Part of Speech: ', 'Synonyms (separated by spaces): ']
, values = []
)
return word_info
for i in range(n):
my_list = get_word()
print my_list # for testing
word, pOS, synonyms = my_list[0], my_list[1], my_list[2]
word = word.capitalize()
synonyms = synonyms.split(', ')
words_list += word
print word # for testing
test_dict[word] = [pOS, synonyms]
print words_list # for testing
However, words_list
ends up being the word(s) after the list(word)
function is applied to them--- I'm not sure why.
For example: if the only word was 'word', words_list
turns out to be ['w', 'o', 'r', 'd']
. If there were two words ('dog', 'cat'), words_list
turns out to be ['d', 'o', 'g', 'c', 'a', 't']
.
Here is my input (into get_word()
): Word: 'myword', Part of Speech: 'n', Synonyms: 'synonym, definition'.
This is the output I get:
['myword', 'n', 'synonym, definition']
Myword
['M', 'y', 'w', 'o', 'r', 'd'] # Why does this happen?
This is the only thing wrong with my program... If I could get some input on how to fix this and what is wrong, it would be much appreciated. Thanks!
Upvotes: 0
Views: 363
Reputation: 48584
It's because of this line:
words_list += word
+=
on a list is for adding all the elements in another list. As it happens, Python strings also function like lists of characters, so you are adding each character to the list as its own element.
You want this:
words_list.append(word)
which is for adding a single element to the end.
Upvotes: 6
Reputation: 17552
After messing around with it, I figured out the problem myself, so I thought I should put it here for anyone who has something similar:
Instead of doing words_list += word
, it should be: words_list.append(word)
.
Or, which is what I did, you can do: words_list += [word]
. Now, word
is a list
object, so it will add onto the previous list.
Upvotes: 0