‘’’
-- encoding: utf-8 --
@Time:不定期更新大数据分析、机器学习等方面的想法和知识
@Desc:删除字符串多余空格及删除多余的空格与空行
‘’’
方法1. 通过字符串的replace方法去掉所有的空格
test = 'I love python '
test_new1 = test.replace(" ", "")
print(test_new1)
方法2. 通过字符串的 split方法 与 join 结合
test_new = test.split(' ')
test_new3 = ''.join(test_new)
方法3. 使用 python 的正则表达式 re
import re
strinfo = re.compile(' ')
test_new2 = strinfo.sub('',test)
string = " * it is blank space test * "
str_new4 = re.sub(r"\s+", " ", string) #多个连续空格合并成一个空格
print(str_new4)
str_new5=' '.join(string.split())
print(str_new5)
如要要删除文字中多余的空格和空行:
str1=re.sub('[\n]+', '\n', 'dfadf d\n \n\n \nfa ds ')
print(str1)
去掉左右两边的空格strip()
string = " * it is blank space test * "
print (string.strip())#rstrip()删除右边空格lstrip()删除左边空格
产出列表中的所有空格
list1 = ['122','2333','3444',' ','422',' ',' ','54',' ']
list_new = [x for x in list1 if x!=' ']
print(list_new)
毕业4年,从应届生到BI数据分析师老油条,不定期将过去自己求职积累经验和数据分析学习相关的一些笔记分享给大家,对互联网数据分析、机器学习有兴趣的朋友也可以关注我的工重号:python数据分析和机器学习,专注BI、数据分析和机器学习的学习和实践 .