By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,589 Members | 1,017 Online
Bytes IT Community
+ Ask a Question
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
  1. lista = [0,'f',0,1,1,1,0,'a',8]
  2. split_length = 3
  3. stringa = ''
  4.  
  5. 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
  1. XX
  2. Traceback (most recent call last):
    File "<stdin>", line 4 in <module>
    TypeError: list indices must be integers, not str
  3.  
Do I need to convert this into tuples of the length desired, or is there a different way?
Mar 1 '12 #1

✓ answered by Smygis

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']

Share this Question
Share on Google+
1 Reply

Smygis
100+
P: 126
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']
Mar 1 '12 #2

Post your reply

Sign in to post your reply or Sign up for a free account.