Python string的一些用法


转载  2013年03月05日 09:35:57
  • 2390

Python string的一些用法

在线文档http://docs.python.org/3.3/library/stdtypes.html#str

1. str.split(sep=None, maxsplit=-1)

http://docs.python.org/3.3/library/stdtypes.html#str.split

sep:分割符;

maxsplit:分割次数, -1代表整个字符串查都分割

For example:

' 1  2   3  '.split() returns ['1', '2', '3']

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

代码1

>>> str1 = ("i am a worker, and you are a student !")

>>> print(str1)

i am a worker, and you are a student !

>>> items = str1.split()

>>> print(items)

['i', 'am', 'a', 'worker,', 'and', 'you', 'are', 'a', 'student', '!']

代码2

>>> str1 = "abcbdbebfbbh"

>>> items = str1.split("b")

>>> print(items)

['a', 'c', 'd', 'e', 'f', '', 'h']

从代码1可以知道默认分割符是空格" ".

从代码2可以知道分割出来的元素两端的空字符会清除.

从代码2可以知道返回列表的第-2项是空的也就是说元素的内容就是两个b之间的去掉两端空字符的内容.

举例分析下载下来的网页的编码方式

[python]  view plain  copy
  1. #!/usr/bin/env python  
  2. # 3.py  
  3. # use UTF-8  
  4. # Python 3.3.0  
  5. def extract(text, sub1, sub2):  
  6. """ 
  7. extract a substring from text between first 
  8. occurances of substrings sub1 and sub2 
  9. """  
  10. return text.split(sub1, 1)[-1].split(sub2, 1)[0]  
  11. str = '...nt="text/html;charset=utf-8">  <title>...'   # 这里是模拟下载下载的某html文件  
  12. print(extract(str, "charset="'"''"'))     # 分割点1"charset=", 分割点2'"'  
  13. # text.split(sub1, 1)[-1].split(sub2, 1)[0]  
  14. # text.split(sub1, 1)[-1]返回的是'utf-8">  <title>...'  
  15. # text.split(sub1, 1)[-1].split(sub2, 1)[0]返回的是 utf-8  

举例: 分割字符串后, 使用":"连接各个字符

[python]  view plain  copy
  1. #!/usr/bin/env python  
  2. # 3.py  
  3. # use UTF-8  
  4. # Python 3.3.0  
  5.   
  6. str = ("i am a worker, and you are a student !")  
  7. items = str.split()  
  8. print(items)  
  9.   
  10. #join the str  
  11. sep = ":"  
  12. items=sep.join(items)  
  13. print(items)  
  14.   
  15. # 输出   
  16. # ['i', 'am', 'a', 'worker,', 'and', 'you', 'are', 'a', 'student', '!']  
  17. # i:am:a:worker,:and:you:are:a:student:!  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值