【转】Python实现将多行格式化的字符串进行压缩

参考:https://blog.csdn.net/u013032479/article/details/106384089/

#-*- coding: utf-8 -*-
'''
======================================================================
描述:将多行格式化的字符串进行压缩
        (例如格式化的sql,替换多余的空格和换行符进行压缩为一行字符串)
作者:xiawp
日期:2020年5月27日 14:24:48
收获:
   思路:通过split拆分‘/n’,挨个执行trim,重新join组合
    python中 类似 “trim”的函数是:strip() 、 lstrip() 、 rstrip()
    python中有比较好用的按行拆分函数:splitlines() ;该函数携带Boolean参数默认false,
        设为true即 str末尾 保留'
'、'
' 等换行符。
======================================================================
'''
 
# 换行格式字符串压缩
def strCompress (strLines):
    #print (strLines);
    strArr = [];
    splitArr = strLines.splitlines();
    for s in splitArr:
        strArr.append(s.strip());
    
    returnStr = (' '.join(strArr));
    #print (returnStr);
 
    return returnStr;
# end strCompress
 
def main ():
    sqlStr = '''
        select
        count(1)
        from test_table
        ''';
    print ("压缩之前:
", sqlStr);
    sqlStr = strCompress(sqlStr)
    print ("压缩之后:
", sqlStr);
 
print ("Hello Python Str Compress
")
main()
print ("
The End!")
 
 
'''
执行结果:
------------------------------------------------------------------------------------------------------------------------
---------- python ----------
Hello Python Str Compress
压缩之前:
 
        select
        count(1)
        from test_table
        
压缩之后:
  select count(1) from test_table 
The End!
输出完成 (耗时 0 秒) - 正常终止
------------------------------------------------------------------------------------------------------------------------
'''
原文地址:https://www.cnblogs.com/ycc1/p/14038758.html