Python如何删除多余的空格与空行(有代码)
方法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([ ]+, , dfadf d fa 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)