【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  '].

 

转载于:https://www.cnblogs.com/cacique/archive/2012/07/23/2604512.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值