How to convert a str to a single element list in python

前端 未结 5 459
无人共我
无人共我 2020-12-29 03:08

I have a str variable: var_1 = \"hello\" , and I want to convert it to a single element list, I try this:

>>>         


        
相关标签:
5条回答
  • 2020-12-29 03:47

    It can be useful to add a check before doing so, as such:

    if not isinstance(var_1, list): var_1 = [var_1]
    

    A use case for this code is in functions that can take either a string or a list of strings and want the functions to handle that silently. E.g.:

    def dataframe_key_columns(dataframe, keys):
        if not isinstance(keys, list): keys = [keys]
        return [dataframe[key] for keys in keys]
    
    0 讨论(0)
  • 2020-12-29 03:51

    Just do the following:

    var_1 = ['hello']
    
    0 讨论(0)
  • 2020-12-29 04:01

    Does var1 = [var1] accomplish what you're looking for?

    0 讨论(0)
  • 2020-12-29 04:09

    Just put square brackets

    >>> var_1 = "hello"
    >>> [var_1]
    ['hello']
    
    0 讨论(0)
  • 2020-12-29 04:11

    Let me provide you a much easier and authentic way to do it.

    s='hello' L=[] L.append(s)

    You will get a list with 'hello' as its element. And you can use the list L anyway you like.

    0 讨论(0)
提交回复
热议问题