Skip to content Skip to sidebar Skip to footer

Is It Possible To Prevent A String From Being Treated Like A List?

Is there any syntax in python to ensure that a given string is not processed as a list? I periodically end up seeing strings iterated through as a list of characters when not inten

Solution 1:

Here's a possible workaround that leverages the fact that strings aren't mutable.

It doesn't throw an Exception, but instead merely converts the object into a list.

from collections.abc import MutableSequence

deflistify(obj):
    return obj ifisinstance(obj, MutableSequence) else [obj]

something = 'Monty'for elem in listify(something):
    ...

I got the basic idea from this answer.

Post a Comment for "Is It Possible To Prevent A String From Being Treated Like A List?"