zoukankan      html  css  js  c++  java
  • 【转】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 秒) - 正常终止
    ------------------------------------------------------------------------------------------------------------------------
    '''
  • 相关阅读:
    《剑指offer》39题—数组中出现次数超过一半的数字
    常见排序算法实现
    剑指offer题目分类
    腾讯2019实习面试题
    Word2vec资料
    Hello World投票以太坊Dapp教程-Part1
    以太坊开发框架Truffle学习笔记
    linux查看端口进程占用情况
    重置fedora root密码
    docker挂载本地目录的方法总结
  • 原文地址:https://www.cnblogs.com/ycc1/p/14038758.html
Copyright © 2011-2022 走看看