开发者

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. some开发者_Python百科text

It must be a list.

Thanks!


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

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


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


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


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)


Use .rstrip():

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜