Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a string into a list without getting split into characters

Tags:

python

People also ask

How do I convert a string to a list without splitting in Python?

One of these methods uses split() function while other methods convert the string into a list without split() function. Python list has a constructor which accepts an iterable as argument and returns a list whose elements are the elements of iterable. An iterable is a structure that can be iterated.

Can you put strings in a list?

Adding a string to a list inserts the string as a single element, and the element will be added to the list at the end. The list. append() will append it to the end of the list.


To add to the end of the list:

list.append('foo')

To insert at the beginning:

list.insert(0, 'foo')

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


Another option is using the overloaded + operator:

>>> l = ['hello','world']
>>> l = ['foo'] + l
>>> l
['foo', 'hello', 'world']

best put brackets around foo, and use +=

list+=['foo']