在python中只加入带空格的行

时间:2014-11-12 06:20:11

标签: python python-2.7

我有以下数据..您可以在开头看到2行之间的空格,而其他行之间没有空格:

Report Area

Total Population

Total Land Area
(Square Miles)

Population Density 
(Per Square Mile)


Report Area 37,325,068 155,738.02 239.67 
Alameda County, CA 1,515,136 738.82 2,050.75 
Alpine County, CA 1,197 738.13 1.62 
Amador County, CA 37,764 594.43 63.53 
Butte County, CA 220,101 1,636.03 134.53 
Calaveras County, CA 45,507 1,019.74 44.63 
Colusa County, CA 21,329 1,150.43 18.54 

我需要最终输出:

Report Area  Total Population  Total Land Area(Square Miles)  Population Density(Per Square Mile)

Report Area 37,325,068 155,738.02 239.67 
Alameda County, CA 1,515,136 738.82 2,050.75 
Alpine County, CA 1,197 738.13 1.62 
Amador County, CA 37,764 594.43 63.53 
Butte County, CA 220,101 1,636.03 134.53 
Calaveras County, CA 45,507 1,019.74 44.63 
Colusa County, CA 21,329 1,150.43 18.54 

我尝试过使用output = " ".join(line.strip( ) for line in f) 但它不能按我的需要工作。

这是我的输出:

Report Area  Total Population  Total Land Area (Square Miles)  Population Density (Per Square Mile)   Report Area 37,325,068 155,738.02 239.67 Alameda County, CA 1,515,136 738.82 2,050.75 Alpine County, CA 1,197 738.13 1.62 Amador County, CA 37,764 594.43 63.53

一行中的所有行..

2 个答案:

答案 0 :(得分:1)

使用条件列表理解:

output = os.linesep.join(line for line in f if " " in line)

答案 1 :(得分:1)

    import re
p = re.compile(ur'\n\n|\n(?=[^\n]*\n\n)', re.IGNORECASE)
test_str = u"Report Area\n\nTotal Population\n\nTotal Land Area\n(Square Miles)\n\nPopulation Density \n(Per Square Mile)\n\n\nReport Area 37,325,068 155,738.02 239.67 \nAlameda County, CA 1,515,136 738.82 2,050.75 \nAlpine County, CA 1,197 738.13 1.62 \nAmador County, CA 37,764 594.43 63.53 \nButte County, CA 220,101 1,636.03 134.53 \nCalaveras County, CA 45,507 1,019.74 44.63 \nColusa County, CA 21,329 1,150.43 18.54 "
subst = u" "

result = re.sub(p, subst, test_str)

您可以通过re尝试。