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"
.