Ruslan Aldongarov
Ruslan Aldongarov

Reputation: 3

Python prints string as list of characters

def make_word_list(file_object):
    return [line.strip() for line in file_object]

def is_anagram(s1, s2):
    return sorted(s1) == sorted(s2)

def find_anagrams(word_list):
    anagram_dict = {}
    for word in word_list:
        k = str(sorted(word))
        anagram_dict[k] = anagram_dict.get(k, []) + [word]

    for k, v in sorted(anagram_dict.items()):
        if len(v) > 1:
            print(str(k), str(v))

if __name__ == '__main__':
    fin = open('words.txt')
    word_list = make_word_list(fin)
    find_anagrams(word_list)

When I run this program, it keeps printing string (the 'k' one) as list of strings. I checked type and it confirmed it's a string. Please help.

Upvotes: 0

Views: 1355

Answers (1)

Parthanon
Parthanon

Reputation: 388

str returns the string representation of what you give it. On a list it will print the items as a list.

Instead you need to join the characters back into a string with

"".join(sorted(word))

"".join(list) adds all the elements in the list together, separated by what is in the quotes. As if you were writing

lst= [1,2,3]
result = []
separator = ","
for i in list:
     result = result + "," + i
result = result[len(separator):] # Remove the first separator

Upvotes: 1

Related Questions