0

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!

1
  • what does this have to do with "splitting a list" (your title)? I am trying to see but I do not see yet. Commented Feb 5, 2015 at 16:18

5 Answers 5

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

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

2 Comments

A regular expression would be overkill for a simple replace.
Was a downvote really necessary? My answer wasn't wrong. There are better answers and I'll admit that.
0

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)

Comments

0

Use .rstrip():

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.