# [Tutor] A list of ints to a strings

Sat Aug 26 00:45:28 CEST 2006

```HTH

wat i ment is like i have

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

and i want x and y as a string

and i want to write it to a file so its like

1 2 3 4 5
2 3 4 5 1

On 8/25/06, John Fouhy <john at fouhy.net> 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
>
> >>> 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.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060825/6d352aaa/attachment.htm
```