creativz
creativz

Reputation: 10807

Split list in python

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!

Upvotes: 0

Views: 846

Answers (5)

ghostdog74
ghostdog74

Reputation: 343097

Use .rstrip():

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

Upvotes: 0

Lee-Man
Lee-Man

Reputation: 414

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)

Upvotes: 0

Alexander Gessler
Alexander Gessler

Reputation: 46657

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

Upvotes: 1

Ipsquiggle
Ipsquiggle

Reputation: 1856

mylist = [s.replace("\r", " ") for s in mylist]

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

Upvotes: 5

calico-cat
calico-cat

Reputation: 1322

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

Upvotes: 0

Related Questions