Convert a string to a list of length one

I created a method that requires a list to work correctly. However, you can send a list or just a string. I want to turn this string into a list containing the whole whole string as an element. For example, if I have:

"I am a string"

      

I want to convert this:

["I am a string"]

      

I can do it like this:

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

      

Since I will never have such a combination of characters, it will always convert it to a list without removing any characters. However, this doesn't seem like something that can be done. Is there another way?

+3


source to share


4 answers


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

      

Putting a value in square brackets makes a list with one element, just as multiple values ​​make a list with multiple elements. The only container that doesn't follow this pattern is a tuple, since parentheses are also used for grouping. In this case, just add a comma after the single element:

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

      



If you want your function to treat list and strings differently under the cover, enter the following command:

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

      

+8


source


If you are trying to accept either a single string or a list of strings as input to a function, but then want to make sure that you are always working with a list in subsequent parts of your code, you can check the type of the argument and convert as needed:

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

listify("hello")
['hello']

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

      



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

+2


source


Here's one quick way:

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

      

... notice that it .append()

adds one item to the list and .extend()

adds a sequence of items to the list.

The problem you're running into is that a Python string is also a sequence of characters (and therefore "iterable"). So, something like: list(myString)

treats myString

as if it will handle any other iterations. (Conceptually, this is done by creating an empty list, iterating over the contents of the initialization, and adding each to the newly created list.)

+2


source


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

      

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

You can also write a one-line file using the ternary operator (introduced with Python 2.5):

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

      

+2


source







All Articles