python中nums.count()什么意思_python count返回什么

a4347c2c4c8e1e3fa0e69735ee2af2ba.png

描述

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

语法

count() 方法语法:S.count(sub[,start=0[,end=len(S)]])

参数

sub -- 搜索的子字符串。

S -- 父字符串。

start -- 可选参数,字符串开始搜索的位置索引,默认为0。(可单独指定)

end -- 可选参数,字符串结束搜索的位置索引,默认为字符串的长度。(不能单独指定)

返回值

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

实例

以下实例展示了 count() 方法的实例:#!/usr/bin/python3

S="www.runoob.com"

sub='o'

print ("S.count('o') : ", S.count(sub))

sub='run'

print ("S.count('run', 0, 10) : ", S.count(sub,0,10))

以上实例输出结果如下:S.count('o') :  3

S.count('run', 0, 10) :  1

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
import os import random import shutil # 步骤1:创建文件并进行删除确认 file_path = '' if os.name == 'nt': # Windows系统 file_path = 'D:\\test.txt' elif os.name == 'posix': # Linux系统 file_path = '\\usr\\local\\test.txt' else: print("不支持的操作系统!") exit(1) if os.path.exists(file_path): while True: delete_choice = input(f"文件 {file_path} 已存在,是否删除并重新创建? (y/n): ") if delete_choice.lower() == 'y': os.remove(file_path) print(f"文件 {file_path} 已删除!") break elif delete_choice.lower() == 'n': print("请手动删除文件后重新运行程序!") exit(1) else: print("输入无效,请重新输入!") # 步骤2:随机写入10个小数并检查是否满足要求 neg_count = 0 while neg_count < 2: random_nums = [round(random.uniform(-1, 1), 2) for _ in range(10)] neg_count = sum(1 for num in random_nums if num < 0) with open(file_path, 'w') as file: file.write(','.join(map(str, random_nums))) print("已创建文件 {} 并已写入 10 个随机数据!".format(file_path)) # 步骤3:读取文件的小数并排序 with open(file_path, 'r') as file: nums_str = file.read().strip() nums_list = list(map(float, nums_str.split(','))) print("从D:\\test.txt读取到的数据为:".format(file_path, nums_str)) print(nums_str) sorted_nums_list = sorted(nums_list, reverse=True) # 修改为排序后的列表 sorted_nums_str = ','.join(map(str, sorted_nums_list)) # 修改为排序后的字符串 # 步骤4:删除小数点、负号和逗号 sorted_nums_str = sorted_nums_str.replace(',', '') print('排序之后得到的字符串为:') print(sorted_nums_str) sorted_nums_str = sorted_nums_str.replace('.', '').replace(',', '').replace('0','') sorted_nums_int = (sorted_nums_str) formatted_result = format(sorted_nums_str) print("经过处理之后的字符串为:\n{}".format(formatted_result)) # 步骤5:追加计算结果到文件 with open(file_path, 'a') as file: file.write('\n' + formatted_result) print("已追加该数值!".format(file_path)) src_file = r'D:\test.txt' dst_file = r'D:\test_solved.txt' shutil.copy2(src_file,dst_file) print('已移动至当前目录!') print('已改名!') print('程序运行完毕!')
05-10

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值