Adag89
Adag89

Reputation: 161

Trying to create an array. Keep getting TypeError

I'm trying to get a better grasp on the data structures. I've been trying to add an array as an element of another array, but i keep getting the TypeError: Array item must be unicode character, when I try to create an array. I'm following videos/everything I read to a T from what i can tell.

from array import array

Swords = array('u',['Steel Sword', 'Bronze Sword', 'Iron Sword'])
Axes = ['Steel Axe', 'Bronze Axe', 'Iron Axe']
Maces = ['Steel Mace','Bronze Mace','Iron Mace']
Bows = ['Wood Bow', 'Bone Bow', 'Obsidian Bow']
Daggers = ['Steel Dagger', 'Bronze Dagger', 'Obsidian Dagger']

Weapons = array('u',([Swords])

for i in Weapons:

    print(i)

Any idea what is going on?

Upvotes: 1

Views: 2825

Answers (1)

Mr. Kelsey
Mr. Kelsey

Reputation: 530

The 'u' type code corresponds to Python’s obsolete unicode character. This means it will work with unicode characters. You can test this

test_one = array("u", ["\u2641","\u2642","\u2643"])
for i in test_one:
    print(i)

You can also see it with this

test_two = array("u", ["T","e","s","t"])
for i in test_two:
    print(i)

Notice, in both cases it is a single character. Not entire strings. In order to do the string, you would have to convert each string to a list of characters.

test_three = array("u", [ch for ch in "Test"])
for i in test_three:
    print(i)

Lastly, if you want to break down the individual characters from a list of strings you can do a list comprehension similar to test_three or you can use a generator.

def character_generator(word_list):
    for word in word_list:
        for ch in word:
            yield ch

test_four = array("u", character_generator(["Test","One","Two"]))
for i in test_four:
    print(i)

At the end of the day though, the u typecode is for individual characters. Not strings.

Upvotes: 2

Related Questions