您的位置:首页 > 编程语言 > Python开发

python3 字符串的相关函数的用法

2018-02-01 19:41 302 查看
string = 'adadjnjjbvjbjnjcbdadab'
# 找出a的位置,使用find函数,如果找到了返回的是小字符开始的位置,如果没找到返回的就是-1
# sub 要查找位置的字符串 start开始查找的位置   end结束查找的位置
index = string.find('a')
print (index)

# 2.index()查找子字符串在大字符串中的位置,如果找到返回起始位置,找不到抛出异常
index = string.index('da')

# 3.count(x,start,end)函数 统计某个字符串在大字符串中出现的次数
count = string.count('b')
print (count)

# 4.转换大小写
# 把字符串全部转换为大写,会把转换之后的字符串返回
upper_str = string.upper()
print (upper_str)

# 5.把字符串全部转换为小写,会把转换之后的字符串返回
lower_str = upper_str.lower()
print (lower_str)

# 6.strip() 去除字符串首尾两端的指定字符,不指定默认去除空格
# chars 要去除的字符
string = '\n张三\n'
strip_str = string.strip('\n')
print (strip_str)

# 7.replace()函数,可以将字符串中的字符进行替换
# old 要替换的字符串  new替换后的字符串 count替换的次数
replace_str = strip_str.replace('\n','==')
print(replace_str)

# 8.split()函数 可以通过的字符对字符串进行分割,分割之后得到的是一个列表
string = '1;2;3;4;5;6;7;8;9'
# seq 指定的分割字符  maxsplit 最大分割次数  不指定就是全部分割
rs = string.split(';')
print (rs)

# 9.join()函数
# iterable 可迭代对象
string = '*'.join(rs)
print (string)

# 10.startswith()函数 判断某个字符串是否以某个字符串开头
# 如果以某个字符开头,返回True 否则返回Flase
print (string.startswith('1'))

# 11.endswith()函数 判断某个字符是否以某个字符串结束
# 如果以某个字符结束,返回True 否则返回Flase
print (string.endswith('10'))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: