Home > OS >  Append strings of different length to array
Append strings of different length to array

Time:01-27

I try to append content from a list looking like this: ["a", "b", "cd"] to an array. It is possible to append "single" strings like "a" and "b" but how do I append the "cd" ?

from array import array


def function(a):
    our_array = array("u",[])
    our_array.insert(0,a)
    print(our_array)


#Working
function("a")

#Not working
function("cd")

CodePudding user response:

array("u",[]) means that the type of our_array elements is wchar_t (docs). As the "cd" is not wchar_t you can't put it into this array. You can use list for that purpose. For example:

def function(a):
    our_list = []
    our_list.append(a)
    print(our_list)

CodePudding user response:

The array interface only allows adding a single element using .append, and the string 'ab' is not a single element for an array of the u type.

Suppose we have an existing array

x = array('u', 'cd')

To prepend 'ab', simply make another array from that string, and then insert it by using slicing:

x[:0] = array('u', 'ab')

Or concatenate the arrays and assign back:

x = array('u', 'ab')   x

Or iterate over the string:

for position, c in enumerate('ab'):
    x.insert(position, c)

Note that each insertion changes the position where the next value should be inserted, so we need to count upwards with the index. enumerate is the natural tool for that.

CodePudding user response:

"".join() allows you to do exactly that.

I refactored the function like so:

def function(a):
    letters = []
    for letter in a:
        letters.append(letter)
    our_array = array("u","".join(letters))
    print(our_array)
  • Related