Adding elements of list into a string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • James Carpenter
    New Member
    • Feb 2012
    • 4

    Adding elements of list into a string

    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.
    Code:
    lista = [0,'f',0,1,1,1,0,'a',8]
    split_length = 3
    stringa = ''
    
    while split_length >= 0:[INDENT]print 'XX ',[/INDENT][INDENT]for idx in lista:[/INDENT][INDENT][INDENT]stringa = stringa + str(lista[idx]) + ' ',[/INDENT][/INDENT][INDENT]print 'XX'[/INDENT]
    What I am wanting this to print would be:
    XX 0 f 0 XX

    What I am getting is:
    Code:
    XX
    Traceback (most recent call last):[INDENT]File "<stdin>", line 4 in <module>[/INDENT]
    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?
  • Smygis
    New Member
    • Jun 2007
    • 126

    #2
    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.

    Code:
    >>> l=[0,'f',0,1,1,1,0,'a',8]
    >>> " ".join([str(i) for i in l[: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 :
    Code:
    >>> l=[0,'f',0,1,1,1,0,'a',8]
    >>> l[::-1] #reversing a list
    [8, 'a', 0, 1, 1, 1, 0, 'f', 0]
    >>> l[1:-1:2] #removing the first, last and every other element
    ['f', 1, 1, 'a']

    Comment

    Working...