Python splitlines使用技巧

时间:2023-01-11 01:13:56 


mulLine = """Hello!!!
Wellcome to Python's world!
There are a lot of interesting things!
Enjoy yourself. Thank you!"""

print ''.join(mulLine.splitlines())
print '------------'
print ''.join(mulLine.splitlines(True))


输出结果:
Hello!!! Wellcome to Python's world! There are a lot of interesting things! Enjoy yourself. Thank you!
------------
Hello!!!
Wellcome to Python's world!
There are a lot of interesting things!
Enjoy yourself. Thank you!

利用这个函数,就可以非常方便写一些段落处理的函数了,比如处理缩进等方法。如Cookbook书中的例子:


def addSpaces(s, numAdd):
white = " "*numAdd
return white + white.join(s.splitlines(True))
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( ) ])
def unIndentBlock(s):
return delSpaces(s, min(numSpaces(s)))
标签:Python,splitlines
0
投稿

猜你喜欢

  • Python实现图片格式转换

    2023-08-03 04:58:57
  • Python深入浅出分析enum枚举类

    2022-07-07 15:09:14
  • Python中拆分字符串的操作方法

    2023-12-20 00:43:24
  • 网页设计趋势之:”勾引”用户的按钮

    2009-02-17 12:09:00
  • Python实现自定义读写分离代码实例

    2023-04-19 14:34:57
  • JS本地刷新返回上一页代码

    2023-08-06 13:59:57
  • Node.js模块全局安装路径配置方法

    2024-05-13 09:28:11
  • 使用php来实现网络服务

    2024-06-05 09:46:46
  • 通过mod_python配置运行在Apache上的Django框架

    2021-07-09 17:54:45
  • uniapp使用H5调试时跨域问题解决

    2024-05-09 10:37:11
  • python 使用elasticsearch 实现翻页的三种方式

    2021-03-09 17:39:57
  • TensorFlow数据输入的方法示例

    2022-04-27 03:32:03
  • Django如何自定义model创建数据库索引的顺序

    2024-01-24 23:14:40
  • 什么是用户体验优化(UEO)

    2008-08-27 19:49:00
  • 小技巧解决“FF不能读取outerHTML”的问题

    2009-02-10 10:44:00
  • Sun拟10亿美元收购MySQL

    2008-01-17 11:56:00
  • Django使用Profile扩展User模块方式

    2023-06-16 12:26:12
  • 详解Python中的join()函数的用法

    2021-01-20 11:21:23
  • python中sqllite插入numpy数组到数据库的实现方法

    2024-01-16 20:31:29
  • go语言实现猜数字小游戏的方法

    2024-02-12 11:47:18
  • asp之家 网络编程 m.aspxhome.com