464,589 Members | 1,017 Online
Need help? Post your question and get tips & solutions from a community of 464,589 IT Pros & Developers. It's quick & easy.

# Adding elements of list into a string

 P: 4 Good day, I am trying to use a list of integers and strings, take certain elements out, and concatenate them into a string. i.e. Expand|Select|Wrap|Line Numbers lista = [0,'f',0,1,1,1,0,'a',8] split_length = 3 stringa = ''   while split_length >= 0:print 'XX ',for idx in lista:stringa = stringa + str(lista[idx]) + ' ',print 'XX' What I am wanting this to print would be: XX 0 f 0 XX What I am getting is: Expand|Select|Wrap|Line Numbers XX Traceback (most recent call last):File "", line 4 in TypeError: list indices must be integers, not str   Do I need to convert this into tuples of the length desired, or is there a different way? Mar 1 '12 #1

I'm not sure what's going on there but I think you should look in to the join attribute of strings as well as slicing.

Expand|Select|Wrap|Line Numbers
1. >>> l=[0,'f',0,1,1,1,0,'a',8]
2. >>> " ".join([str(i) for i in l[:3]])
3. '0 f 0'
Its much easier to create a list and then join it together in to a string.

Slicing works as follows sequence[x:y:z] where;
sequence = any list tuple or string
x = the starting element, empty means start of the sequence
y = the end of the slice, empty is the end
z = stepping of the slicing for instance 2 is every other element, not required as it defaults to 1.

example :
Expand|Select|Wrap|Line Numbers
1. >>> l=[0,'f',0,1,1,1,0,'a',8]
2. >>> l[::-1] #reversing a list
3. [8, 'a', 0, 1, 1, 1, 0, 'f', 0]
4. >>> l[1:-1:2] #removing the first, last and every other element
5. ['f', 1, 1, 'a']