Python string的一些用法

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之间的去掉两端空字符的内容.

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

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

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

#!/usr/bin/env python
# 3.py
# use UTF-8
# Python 3.3.0

str = ("i am a worker, and you are a student !")
items = str.split()
print(items)

#join the str
sep = ":"
items=sep.join(items)
print(items)

# 输出 
# ['i', 'am', 'a', 'worker,', 'and', 'you', 'are', 'a', 'student', '!']
# i:am:a:worker,:and:you:are:a:student:!


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值