user2869231
user2869231

Reputation: 1541

Convert a string to a list of length one

I created a method that requires a list in order to work properly. However, you can send in a list OR a simple string. I want to turn that string into a list that contains that entire string as an element. For example, if I have:

"I am a string"

I want to convert that to:

["I am a string"]

I am able to do it like so:

"I am a string".split("!@#$%^&*")

Because I will never have that combination of symbols, it will always convert it to a list without removing any characters. However, this doesn't seem like that great of a way to do it. Is there another way?

Upvotes: 3

Views: 10936

Answers (4)

mattsilver
mattsilver

Reputation: 4396

If you're trying to accept either a single string or a list of strings as the input to a function, but then want to ensure that you're always working with a list in subsequent portions of code, you can check the type of the argument and convert if necessary:

def listify(arg):
    return arg if isinstance(arg, list) else [arg] 

listify("hello")
['hello']

listify(["hi", "howdy"])
['hi', 'howdy']

This doesn't have to occur as a separate function, I just put it in a function to illustrate quickly. You can also directly assign to a variable instead of returning.

Upvotes: 3

Yaroslav Nikitenko
Yaroslav Nikitenko

Reputation: 1853

>>> s = "abc"
>>> if isinstance(s, str): 
...    s = [ s ]
>>> s 
['abc']

As proposed earlier, you can make this check a separate function.

You can also write a one-liner using a ternary operator (introduced since Python 2.5):

s = s if isinstance(s, list) else [ s ]

Upvotes: 3

matsjoyce
matsjoyce

Reputation: 5844

>>> "abc"
'abc'
>>> ["abc"]
['abc']
>>> abc = "abc"
>>> abc
'abc'
>>> [abc]
['abc']
>>> "I am a string".split("!@#$%^&*") == ["I am a string"]
True

Putting the value in square brackets makes a list with one item, just as multiple values makes a list with multiple items. The only container which does not follow this pattern is the tuple, as the round brackets are also used for grouping. In that case, just add a comma after the single item:

>>> abc
'abc'
>>> (abc)
'abc'
>>> (abc,)
('abc',)

If you want your function to handle list and strings differently under the cover, code your function like:

def f(maybe_list):
    if not isinstance(maybe_list, list):
        maybe_list = [maybe_list]
    # carry on, you have a list.

Upvotes: 9

Jim Dennis
Jim Dennis

Reputation: 17530

Here's one quick way:

#!python
myString = 'some string'
myList = list()
myList.append(myString)

... note that .append() adds a single item to a list while .extend() adds a sequence of items to a list.

The problem you're encountering is that a Python string is also a sequence of characters (and is thus an "iterable"). So something like: list(myString) treats myString like it would treat any other iterable. (Conceptually that's done by instantiating an empty list, iterating over the initialization contents and appending each to the newly instantiated list).

Upvotes: 2

Related Questions