-1

I have the following array

([[ 1,  1,  2,  2],
   [ 1,  1,  3,  3],
   [ 1,  1,  4,  4]])

I want to convert values from int to str, like this:

([[ '1',  '1',  '2',  '2'],
   [ '1',  '1',  '3',  '3'],
   [ '1',  '1',  '4',  '4']])

How can I do this?

4
  • When you say you have an array, are you referring to Python's array.array type or a numpy.ndarray type? Or - do you have a native Python list of lists? May 30, 2018 at 16:36
  • array dtype=int64
    – Elmoro
    May 30, 2018 at 16:39
  • 1
    So does your_variable_name.astype(str) do what you want then? May 30, 2018 at 16:39
  • Yes!!! Thank you!
    – Elmoro
    May 30, 2018 at 16:41

2 Answers 2

0

arr being your array with ints, you can do:

list(map(lambda i: list(map(str,i)), arr)) with a one liner.

The result:

[['1', '1', '2', '2'], ['1', '1', '3', '3'], ['1', '1', '4', '4']]

0

The following might work:

def stringify_nested_containers(obj):
    if hasattr(obj, '__iter__') and not isinstance(obj, str):
        obj = list(obj)
        for idx in range(0, len(obj)):
            obj[idx] = stringify_nested_containers(obj[idx])
    else:
        obj = str(obj)
    return obj

Example Usage:

lyst = [
            [ 1,  1,  2,  2],
            [ 1,  1,  3,  3],
            [ 1,  1,  4,  4]
]

slyst = stringify_nested_containers(lyst)
print(slyst)
print(type(slyst[0][0]))

Warning:

For a string named stryng, stryng[0], stryng[539], or stryng[whatever] are not characters, they are strings.

Thus,

"h" == "hello world"[0]

and

"h" == "hello world"[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0]

Suppose you try to dig down into nested containers until you reach to an object which does not have an __iter__ method (i.e. a non-container). Suppose there is a string in your nested container. Then you will end up in an infinite recursion or loop because "a"[0] is iterable for any character "a". Specifically "a" has one element, "a"[0] and "a"[0]== "a".

Not the answer you're looking for? Browse other questions tagged or ask your own question.