2013-07-11 14 views
0

我有一个字符串,它看起来像这样,当我打印:删除linespacing

RT @HHRoadGuy: It's that time again! Time to tune in for the latest #fortheloveofmusic episode. Catch it now on @CMT! 

http://t.co/VatlhGq9… 

我就先以摆脱linespacing的:

tweet = tweet.rstrip('\r\n') 

但事实并非如此工作。线间距可能介于两者之间。替换功能也无济于事。我能在这里做什么?

+0

*替换函数忍不住* - 以什么方式?你尝试了什么? –

+0

你是对的。真是愚蠢的问题。我的代码中只有一个小错误。抱歉。 tweet = tweet.replace('\ n','') – Tom

回答

0
tweet = tweet.replace('\n','') 

是答案。我只是在我的代码中遇到了一个小错误,并尝试了所有这些不同的方法和我失明的东西。抱歉!

1

你确定行界线确实是'\ r \ n'而不是'\ n'吗? 因为replace()应该只是罚款:

>>> s = 'hello\r\n\r\nhi' 
>>> print(s) 
hello 

hi 
>>> s2 = s.replace('\r\n\r\n', '\r\n') 
>>> print(s2) 
hello 
hi 

事实上,rstrip()将无法​​正常工作,因为该功能仅剥离右侧(结束)的字符串。

1

下应该在大多数情况下摆脱所有换行符的,无论它们是如何表示:

lines = tweet.splitlines() 
tweet = " ".join(lines) 

或者,为了避免双倍间距(并采用PM的概念):

tweet = " ".join([line for line in lines if len(line)]) 

如果您只想摆脱空行但保留行br eaks:

tweet = "\n".join([line for line in lines if len(line)])