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

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

#!/usr/bin/python#-*- coding: utf-8 -*-

#改变多行文本的缩进

defreindent(s,numSpaces):

leading_space= numSpaces * ' 'lines= [leading_space + line.strip() for line ins.splitlines()]return '\n'.join(lines)

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

defaddSpaces(s,numAdd):#计算原有空格数和需要添加的空格数的总和

white = ' ' *numAddreturn white +white.join(s.splitlines)defnumSpaces(s):#返回每行空格数的列表

return [len(line)-len(line.lstrip()) for line ins.splitlines()]defdelSpaces(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 None, chars 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 None, chars 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 None, chars 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  '].

python 多行缩进_【python cookbook】改变多行文本字符串的缩进相关推荐

  1. python反向缩进_在Pycharm中对代码进行注释和缩进的方法详解

    在Pycharm中对代码进行注释和缩进的方法详解 一.注释 1. #单行注释 2. """ 多行注释 """ 3. pycharm多行注释快 ...

  2. python 命令行 模块_深入浅析Python 命令行模块 Click

    Click 是用 Python 写的一个第三方模块,用于快速创建命令行.我们知道,Python 内置了一个 Argparse 的标准库用于创建命令行,但使用起来有些繁琐,Click 相比于 Argpa ...

  3. python统计行号_如何使用Python脚本分析CPU使用情况的?

    用以分析Python中CPU使用情况.CPU分析是通过分析CPU执行代码的方式来测量代码的性能,以此找到代码中的不妥之处,然后处理它们. 接下来我们将看看如何跟踪Python脚本使用时CPU使用情况, ...

  4. python多行显示_设置图例以多行显示(在python中) - python

    我在同一张图中绘制了几条线,我想根据其内容命名这组线.在那些行上,我还没有打算用误差线绘制平均值.但是出现了两个主要问题: 1)我的图例没有按我的预期出现(即使试图在图的范围之外绘制一个额外的点,我也 ...

  5. python查看excel编码格式_[Python]实现处理读写xlsx xls excel文件格式(含中文处理方法)...

    最近有个需求要处理excel 格式的数据,数据量比较大.用传统的语言似乎不太好处理,于是改用python实现,这里记录一下实现过程. 首先,科普一下xlsx xls的excel文件区别是什么. xls ...

  6. python朋友圈刷屏_“Python太火了!请救救Java!”9万程序员刷屏朋友圈 !

    没想到有生之年,笔者能观察到"霸主陨落"的过程,继PLPY4月榜单官宣,Python躺赢,再度"夺"冠,实力甩下Java和C后,近期,Stack Overflo ...

  7. python 打包 小文件_[Python][小知识][NO.5] 使用 Pyinstaller 打包成.exe文件

    1.安装 pyinstaller 插件 cmd命令:pip install PyInstaller PS . o.o 不知道 easy_install 的百度吧. 2.pyinstaller 简介 他 ...

  8. python希腊字母怎么生成_#python sympy怎样把狄克拉函数定义出来#

    Python sympy用integrate解定积分出来的结果不是计算完的结果 ## 数值积分 sympy下的integrate()函数是解析积分,当被积函数不存在原函数时则无法得到节分结果.所以建议 ...

  9. python shell如何打开_“python shell怎么打开“python shell启动教程

    python shell怎么打开 1.简介:如何在python中运行shell(bash命令) 2.工具/原料:python库:os.py 3.方法:import os command = 'date ...

  10. python输出文本居中_#python PIL ImageDraw text 文本居中#

    python pip pil有什么东西 你所问的问题实是属1.先参考[教程]Python中的内置的和方的模块搞懂PIL是属于第三方Python模块2.再参考:[待完善][总结]Python安装第三方的 ...

最新文章

  1. 学习canvas 过程中的几点总结
  2. 《ASCE1885的网络编程》---Winsock APIのIP地址转换函数
  3. Android RecyclerView设计通用Adapter
  4. 负数的补码公式是什么_为什么0xffffffff是-1?(计算机对整型的存储)
  5. Linux中关于API函数与系统调用
  6. svnadmin的使用
  7. zedboard 驱动理解
  8. Windows 10 Insider Preview ISO 下载地址
  9. 京瓷打印机1025默认管理员密码_FW316R默认管理员密码
  10. md文件 linux,MD 文件扩展名: 它是什么以及如何打开它?
  11. LOB类型的学习、总结
  12. 多线程抽取数据库数据,数据迁移
  13. 联想小娜怎么开启_详细教您如何开启win10小娜
  14. 输入的字与系统编码不符_基于小字符集藏文拉丁转写系统的设计与实现
  15. c语言文件读取与写入
  16. JavaScript的返回值
  17. QNAP 威联通(NAS)安装百度云(Linux方案)
  18. h3c 链路聚合测试_H3C设备实验之配置链路聚合
  19. Android-WIFI笔记整理(一)
  20. Eclipse使用SVN进行代码提交的步骤

热门文章

  1. 用css实现了一个精致的纵向导航菜单
  2. 分类目录管理系统——软件开发项目实践
  3. Unity的包体压缩以及音效优化
  4. ctf 选择题 题库_看雪CTF题库平台 | 赛练结合,助你夺冠!
  5. python深复制_Python深浅拷贝
  6. Oracle RAC tns 00505,Alert Log Errors: 12170 TNS-12535/TNS-00505: Operation Timed Out
  7. ant design vue table 高度自适应_Table行内的开关组件的使用
  8. 【转】mutation接收单个参数和多个参数
  9. asp.net中如何解决4M以上文件的上传
  10. 少年时期最后一个儿童节