[Tutor] A list of ints to a strings

2006-08-25 Thread Amadeo Bellotti
I need to convert a list of intgers to a string so for example

I have this
x = [1, 2, 3, 4, 5, 6]

I want this

x = 1 2 3 4 5 6

I need this to write it to a .txt file does anyone know how to do this?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A list of ints to a strings

2006-08-25 Thread Amadeo Bellotti
thank you and like wat if i wanna write one string on one line and another string on another line ect.On 8/25/06, David Heiser 
[EMAIL PROTECTED] wrote:






This 
will work

x = [1, 2, 3, 4, 5, 
6]

x = str(x)[1:-1].replace(,, 
'')

open(filename.txt, 
w).write(x)


  
  -Original Message-From: 
  [EMAIL PROTECTED] [mailto:
[EMAIL PROTECTED]] On Behalf Of 
  Amadeo BellottiSent: Friday, August 25, 2006 3:28 
  PMTo: TutorSubject: [Tutor] A list of ints to a 
  stringsI need to convert a list of intgers to a string so 
  for exampleI have thisx = [1, 2, 3, 4, 5, 6]I want 
  thisx = 1 2 3 4 5 6I need this to write it to a .txt file 
  does anyone know how to do this?


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A list of ints to a strings

2006-08-25 Thread John Fouhy
On 26/08/06, Amadeo Bellotti [EMAIL PROTECTED] wrote:
 I need to convert a list of intgers to a string so for example

  I have this
  x = [1, 2, 3, 4, 5, 6]

  I want this

  x = 1 2 3 4 5 6

Actually, I disagree with David's solution somewhat --- I think that
the pythonic way to do this is as follows:

Firstly, you can use a list comprehension to convert each integer into
a separate string.  If you don't know about list comprehensions, you
can read about them in any python tutorial.

 x = [1, 2, 3, 4, 5]
 y = [str(i) for i in x]
 y
['1', '2', '3', '4', '5']

Then you can use the .join() method of strings to join them into a
single line.  In this case, the separator is a space, ' ':

 z = ' '.join(y)
 z
'1 2 3 4 5'

If you want to put one number on each row, you can use the newline
character '\n' as a separator instead:

 '\n'.join(y)
'1\n2\n3\n4\n5'
 print '\n'.join(y)
1
2
3
4
5

HTH!

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor