python学习--去除空格

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''去除多余的空格
'''

string = "My name    is   hyaden"
print(string)

str_list = string.split(" ")
print(str_list)

words1 = [ s.strip() for s in str_list] # 去除单词两边的空格
print(words1)

new_string1 = " ".join(words1) # 以空格为连接符,将单词链接起来
print(new_string1)

words2 = [s for s in str_list if s != ""] #利用列表解析,将隔空检出
print(words2)

new_string2 = " ".join(words2)
print(new_string2)

 

posted @ 2017-12-11 14:16  hayden__wang  阅读(812)  评论(0编辑  收藏  举报