一丶split方法
help(str.split)
Helpon method_descriptor:split(...)
S.split([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are removed
from the result.
None
根据上述描述,split方法有两个参数,一个是sep表示分隔符,默认按照空白字符串切割,另一个maxsplit表示最多切分的次数,默认按照正常逻辑切割,最后方法返回一个元素为字符串类型的List。
案例如下:
案例1
learnSplit = 'I love python and java'
# 两个参数均为默认
strList = learnSplit.split()
print strList
['I', 'love', 'python', 'and', 'java']
案例2
最多切分次数为1时,返回的list有个元素
learnSplit = 'I love python and java'
strList = learnSplit.split(" ",1)
print strList
['I', 'love python and java']
案例3
当超过最大的切分次数时,默认按照最大切分次数执行
learnSplit = 'I love python and java'
strList = learnSplit.split(" ",5)
print strList
['I', 'love', 'python', 'and', 'java']
案例4
用其他的分割符切分
learnSplit = 'ab,cde,afs,sdss,aaa'
strList = learnSplit.split(",")
print strList
['ab', 'cde', 'afs', 'sdss', 'aaa']
learnSplit = 'ab/cde/afs/sdss/aaa'
strList = learnSplit.split("/")
print strList
['ab', 'cde', 'afs', 'sdss', 'aaa']
二丶strip方法
help(str.strip)
Help on method_descriptor:
strip(...)S.strip([chars]) -> string or unicode
Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
根据上述描述,该方法有一个参数,表示移除首尾指定的字符,默认是空格,返回一个新的字符串。
案例1
默认移除字符串首尾的空格
learnStrip = ' I love python and java '
strr = learnStrip.strip()
print strr
I love python and java
案例2
只有尾部有a字符,所以首部的空格没有去掉,尾部的字符a移除啦
learnStrip = ' I love python and java'
strr = learnStrip.strip("a")
print strr
I love python and jav
案例3
这个字符为a,字符串的首尾是空格,所以返回的是原来的字符串
learnStrip = ' I love python and java '
strr = learnStrip.strip('a')
print strr
I love python and java
案例4
首尾指定的字符是值一个字符串前端和后端的字符,而不是第一个元素和最后一个元素
learnStrip = 'aabbbbbaaaaaa'
print learnStrip.strip("a")
bbbbb
三丶join方法
help(str.join)
Help on method_descriptor:
join(...)S.join(iterable) -> string
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
根据上述描述,该方法有一个参数,是一个可迭代的对象,这个对象里面的元素必须为字符串类型,最后返回一个字符串。
案例
aTuple = ('1', '2', '3', '4')
bTuple = ('a', 'b', 'c', 'd')
aList = ['aa', 'bb', '1', '2']
bList = ["张", '2', "赵", "钱"]
print ",".join(aTuple)
print ",".join(bTuple)
print ",".join(aList)
print ",".join(bList)
1,2,3,4
a,b,c,d
aa,bb,1,2
张,2,赵,钱