learnpythonthehardway EX41 相关

str.count()

# str.count()方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。
# str.count(sub, start= 0,end=len(string))
'''
sub -- 搜索的目标字符串
start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
end -- 字符串中结束搜索的位置。默认为字符串的最后一个位置len(str)。
start、end默认可略
'''

str = "this is string example....wow!!!"
 
sub = "i"
print("str.count(sub, 4, 40) : ", str.count(sub, 4, 40))
sub = "wow"
print("str.count(sub) : ", str.count(sub))

print('str.count(sub, 4, 40) :',str.count('s',0,len(str)))

join()函数

# 'sep'.join(seq)
'''
参数说明
sep:分隔符。可以为空
seq:要连接的元素序列、字符串、元组、字典
上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串

返回值:返回一个以分隔符sep连接各个元素后生成的字符串
'''
# 实例
# ① list
seq=['hello','world','I','like','python']
print(' '.join(seq))
$ hello world I like python

print(':'.join(seq))
$ hello:world:I:like:python

# ② tuple
seq=('hello','world','I','like','python')
print('-'.join(seq))
$ hello-world-I-like-python

# ③ str
seq='helloworldIlikepython'
print('-'.join(seq))
$ h-e-l-l-o-w-o-r-l-d-I-l-i-k-e-p-y-t-h-o-n

# ④ dict
seq={'hello':1,'world':2,'I':3,'like':4,'python':5}
print('-'.join(seq))
$ python-world-like-I-hello  #无序keys

# 合并目录
import os
datafile=os.path.join('/usr/','bin/','deepblue/py3.5_code_linux/')
print(datafile)
$ /usr/bin/deepblue/py3.5_code_linux/
原文地址:https://www.cnblogs.com/deepblue775737449/p/8722709.html