zoukankan      html  css  js  c++  java
  • 【python cookbook】改变多行文本字符串的缩进

    任务:有一个多行文本的字符串 需要创建该字符串的一个拷贝,并在每行行首添加或删除一些空格,以保证每行缩进都是指定数目的空格数

     利用字符串对象提供的    strip()  s.splitlines()可以很快的实现

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    #改变多行文本的缩进
    
    def reindent(s,numSpaces):
        leading_space = numSpaces * ' '
        lines = [leading_space + line.strip()  for line in s.splitlines()]
        return '\n'.join(lines)

    如果要调整每行的空格数 并保证相对缩进不变

    def addSpaces(s,numAdd):
           #计算原有空格数和需要添加的空格数的总和
        white = ' ' * numAdd
        return white + white.join(s.splitlines)
    
    def numSpaces(s):
           #返回每行空格数的列表
        return [len(line)-len(line.lstrip()) for line in s.splitlines()]
    
    def delSpaces(s,numDel):
        if numDel > min(numSpaces(s)):
            raise ValueError,"removing more spaces than there are!"
        return '\n'.join([ line[numDel:] for line in s.splitlines() ])

    s.splitlines() 用法

    str.splitlines([keepends])

    Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. This method uses the universal newlines approach to splitting lines. Unlike split(), if the string ends with line boundary characters the returned list does not have an empty last element.

    For example, 'ab c\n\nde fg\rkl\r\n'.splitlines() returns ['ab c', '', 'de fg', 'kl'], while the same call with splitlines(True) returns ['ab c\n', '\n, 'de fg\r', 'kl\r\n'].

     
    >>> a = """first
             second
             third
             """
    
    >>> a.splitlines()
    ['first', '         second', '         third', '         ']
    
    
    lstrip用法()
    string.lstrip(s[chars])

    Return a copy of the string with leading characters removed. If chars is omitted or None, whitespace characters are removed. If given and not Nonechars must be a string; the characters in the string will be stripped from the beginning of the string this method is called on.

    去除首部指定字符 若不指定 默认去掉空格

    rstrip用法()
    string.rstrip(s[chars])

    Return a copy of the string with trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not Nonechars must be a string; the characters in the string will be stripped from the end of the string this method is called on.

    去除尾部指定字符 若不指定 默认去掉空格

    strip用法()
    string.strip(s[chars])

    Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not Nonechars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.

    去除字符串两端指定字符 若不指定 默认去掉空格

     

     

    str.split([sep[maxsplit]])

    Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

    If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns [''].

    If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

    For example, ' 1  2   3  '.split() returns ['1', '2', '3'], and '  1  2   3  '.split(None, 1) returns ['1', '2   3  '].

    
    
  • 相关阅读:
    hdu 1166 敌兵布阵 线段树区间修改、查询、单点修改 板子题
    POJ 1655 Balancing Act ( 树的重心板子题,链式前向星建图)
    P1268 树的重量(板子)
    P1896 [SCOI2005]互不侵犯 状压dp
    Delphi {$M +} 与{$TYPEINFO ON} 和 {$M -} 与{$TYPEINFO OFF}
    SQL 通过SQL语句检索字段类型、长度、主键
    随笔2020.11.10
    Delphi 操作Windows系统睡眠-防止系统/电脑 进入睡眠或关闭显示器
    Delphi WinAPI SetThreadExecutionState
    Delphi TOpenDialog的使用介绍以及如何动态创建和释放
  • 原文地址:https://www.cnblogs.com/cacique/p/2604512.html
Copyright © 2011-2022 走看看