tags:

views:

108

answers:

5

I have following list:

mylist = ['Hello,\r', 'Whats going on.\r', 'some text']

When I write "mylist" to a file called file.txt

open('file.txt', 'w').writelines(mylist)

I get for every line a little bit text because of the \r:

Hello,
Whats going on.
some text

How can I manipulate mylist to substitute the \r with a space? In the end I need this in file.txt:

Hello, Whats going on. sometext

It must be a list.

Thanks!

A: 

Iterate through the list to a match with a regular expression to replace /r with a space.

calico-cat
A regular expression would be overkill for a simple replace.
sth
Was a downvote really necessary? My answer wasn't wrong. There are better answers and I'll admit that.
calico-cat
+5  A: 
mylist = [s.replace("\r", " ") for s in mylist]

This loops through your list, and does a string replace on each element in it.

Ipsquiggle
A: 
open('file.txt', 'w').writelines(map(lambda x: x.replace('\r',' '),mylist))
Alexander Gessler
A: 

I don't know if you have this luxury, but I actually like to keep my lists of strings without newlines at the end. That way, I can manipulate them, doing things like dumping them out in debug mode, without having to do an "rstrip()" on them.

For example, if your strings were saved like:

mylist = ['Hello,', 'Whats going on.', 'some text']

Then you could display them like this:

print "\n".join(mylist)

or

print " ".join(mylist)
Lee-Man
A: 

use rstrip().

>>> mylist = ['Hello,\r', 'Whats going on.\r', 'some text']
>>> ' '.join(map(str.rstrip,mylist))
'Hello, Whats going on. some text'
>>>
ghostdog74