Inserting a string into a list without getting split into characters

后端 未结 9 1732
孤城傲影
孤城傲影 2020-12-13 16:45

I\'m new to Python and can\'t find a way to insert a string into a list without it getting split into individual characters:

>>> list=[\'hello\',\'w         


        
相关标签:
9条回答
  • 2020-12-13 17:11
    ls=['hello','world']
    ls.append('python')
    ['hello', 'world', 'python']
    

    or (use insert function where you can use index position in list)

    ls.insert(0,'python')
    print(ls)
    ['python', 'hello', 'world']
    
    0 讨论(0)
  • 2020-12-13 17:19

    You have to add another list:

    list[:0]=['foo']
    
    0 讨论(0)
  • 2020-12-13 17:20
    >>> li = ['aaa', 'bbb']
    >>> li.insert(0, 'wow!')
    >>> li
    ['wow!', 'aaa', 'bbb']
    
    0 讨论(0)
  • 2020-12-13 17:22

    To add to the end of the list:

    list.append('foo')
    

    To insert at the beginning:

    list.insert(0, 'foo')
    
    0 讨论(0)
  • 2020-12-13 17:24

    Sticking to the method you are using to insert it, use

    list[:0] = ['foo']
    

    http://docs.python.org/release/2.6.6/library/stdtypes.html#mutable-sequence-types

    0 讨论(0)
  • 2020-12-13 17:25

    best put brackets around foo, and use +=

    list+=['foo']
    
    0 讨论(0)
提交回复
热议问题