Python语言基础
Python语言进阶
Python数据结构

Python count()方法

搞懂Python count()的用法
<<< Python 字符串

描述

count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。

语法

count()方法语法:
str.count(sub, start= 0,end=len(string))

参数

sub -- 搜索的子字符串 start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。 end -- 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。

返回值

该方法返回子字符串在字符串中出现的次数。

实例

以下实例展示了count()方法的实例:
str="www.lidihuo.com"
sub='o'
print ("str.count('o') : ", str.count(sub))
sub='li'
print ("str.count('run', 0, 10) : ", str.count(sub,0,10))
以上实例输出结果如下:
str.count('o') : 2
str.count('run', 0, 10) : 1

Python string更多操作说明

Python String操作方法
capitalize()
第一个字符转换为大写
center(width, fillchar)
返回一个指定的宽度的字符串
count(str, beg= 0,end=len(string))
返回出现次数
bytes.decode(encoding="utf-8", errors="strict")
解码给定的 bytes 对象
encode(encoding='UTF-8',errors='strict')
对字符串进行编码
endswith(suffix, beg=0, end=len(string))
检查是否以 obj 结束
expandtabs(tabsize=8)
把字符串中的tab转为空格
find(str, beg=0, end=len(string))
检测是否包含某个字符串
index(str, beg=0, end=len(string))
跟find()方法相同
isalnum()
所有字符是字母或数字返回True
isalpha()
所有字符都是字母返回True
isdigit()
字符串只包含数字返回True
islower()
字符都是小写返回True
isnumeric()
字符串只包含数字返回 True
isspace()
字符串中只包含空白返回True
istitle()
字符串是标题化的返回 True
isupper()
字符串都是大写返回True
join(seq)
以指定字符串作为分隔符
len(string)
返回字符串长度。
ljust(width[, fillchar])
返回一个原字符串左对齐
lower()
转换大写字符为小写。
lstrip()
截掉字符串左边的字符。
maketrans()
创建字符映射的转换表
max(str)
返回字符串中最大的字母。
min(str)
返回字符串中最小的字母。
replace(old, new [, max])
替换将字符串
rfind(str, beg=0,end=len(string))
类似于find()函数
rindex( str, beg=0, end=len(string))
类似于index()
rjust(width,[, fillchar])
返回一个原字符串右对齐
rstrip()
删除字符串末尾的空格。
split(str="", num=string.count(str))
以str为分隔符截取字符串
splitlines([keepends])
按照行分隔返回元素的列表
startswith(substr, beg=0,end=len(string))
是否是以指定子字符串开头
strip([chars])
执行 lstrip()和 rstrip()。
swapcase()
将字符串中大写转换为小写
title()
返回"标题化"的字符串
translate(table, deletechars="")
转换和过滤掉的字符
upper()
转换字符串中的小写为大写。
zfill(width)
返回长度为width的字符串
isdecimal()
只包含十进制字符返回true
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4