
python中count函数用法的困惑
在学习python过程中,一位新手遇到一个问题。代码如下:
file_name = 'paper1.txt'
with open(file_name) as fn:
lines = fn.readlines()
for line in lines:
line.count('the')当运行此代码时,虽然paper1.txt文件中包含字符"the",但终端中却什么都没有显示,也没有显示数字或错误。
问题出在哪里呢?
立即学习“Python免费学习笔记(深入)”;
答案是,在使用shell命令(例如python xxx.py)运行python脚本时,需要使用print函数来显示结果。修改后的代码如下:
file_name = 'paper1.txt'
with open(file_name) as fn:
lines = fn.readlines()
for line in lines:
print(line.count('the'))现在,运行修改后的代码时,终端将显示文本文件中包含"the"字符的次数。










