Python字符串的count函数

目录

  • count的功能
  • count的用法
  • count的注意事项

count的功能

  • 返回当前字符串中某个成员 (元素) 的个数

count的用法

  • 用法:inttype = string.count(item)
  • 参数:item 查询个数的元素
In [17]: info = 'my name is insaneloafer'
In [18]: print(info.count( 'a' )
2

count的注意事项

  • 如果查询的成员(元素)不存在,则返回0
test_str = 'my name is insane'
count = test_str.count('z')
print(count) -> 0

实战

# coding:utf-8

info = """
     Open source software is made better when users can easily
     contribute code and documentation to fix bugs and add features. 
     Python strongly encourages community involvement in improving the software. 
     Learn more about how to make Python better for everyone.
     Contribute to Python Bug Tracker
"""

a = info.count('a')
b = info.count('b')
c = info.count('c')
d = info.count('d')
e = info.count('e')
f = info.count('f')

print(a, b, c, d, e, f)
number_list = [a, b, c, d, e, f]
print(number_list)
print('在列表中,最大的数值是:', max(number_list))

number_dict = {
    'a': a,
    'b': b,
    'c': c,
    'd': d,
    'e': e,
    'f': f
}
print('每个成员对应的数值是:', number_dict)
15 6 8 7 30 5
[15, 6, 8, 7, 30, 5]
在列表中,最大的数值是: 30
每个成员对应的数值是: {'a': 15, 'b': 6, 'c': 8, 'd': 7, 'e': 30, 'f': 5}

Process finished with exit code 0
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中提供了很多字符串内置函数,这里列举几个比较常用的: 1. `len(str)`:返回字符串的长度。 ```python str = "hello, world!" print(len(str)) # 输出:13 ``` 2. `str.upper()`和`str.lower()`:将字符串分别转化为大写和小写形式。 ```python str = "Hello, WoRlD!" print(str.upper()) # 输出:HELLO, WORLD! print(str.lower()) # 输出:hello, world! ``` 3. `str.capitalize()`和`str.title()`:将字符串的首字母或每个单词的首字母转化为大写。 ```python str = "hello, world!" print(str.capitalize()) # 输出:Hello, world! print(str.title()) # 输出:Hello, World! ``` 4. `str.find(sub, start, end)`和`str.index(sub, start, end)`:返回子字符串在原字符串中的位置,若没有则返回-1或抛出异常。 ```python str = "hello, world!" print(str.find('o')) # 输出:4 print(str.index('o')) # 输出:4 print(str.find('z')) # 输出:-1 # print(str.index('z')) # 抛出异常:ValueError: substring not found ``` 5. `str.count(sub, start, end)`:返回子字符串在原字符串中出现的次数。 ```python str = "hello, world!" print(str.count('o')) # 输出:2 ``` 6. `str.replace(old, new, count)`:将字符串中的所有旧子字符串替换为新子字符串count为替换次数,可省略,表示替换所有。 ```python str = "hello, world!" print(str.replace('l', 'L')) # 输出:heLLo, worLd! ``` 除此之外,还有很多其他的字符串内置函数,比如`str.startswith(prefix, start, end)`、`str.endswith(suffix, start, end)`、`str.strip(chars)`、`str.join(iterable)`等等。这些函数都有其特定的功能和用法,可以根据实际情况进行选择和使用。 引用:Python字符串内置函数功能与用法总结。主要介绍了Python字符串内置函数功能与用法,结合实例形式总结分析了Python常见字符串操作函数的功能、分类、使用方法及相关操作注意事项,需要的朋友可以参考下[^1]。 引用:python string内置函数表格。string.replace(str1, str2, num=string.count(str1)) [^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值