如何修复TypeError:“类型”对象不可下标

时间:2019-06-27 18:01:21

标签: python python-3.x

我正在接受老师的编码挑战,由于某种原因,在实现自定义字符串输入以供用户添加自己的字符串之前,我无法使最后几行代码起作用。

我尝试完全更改编码类型,但仍然无法正常工作,每次都遇到相同的问题。

import string 
strg = "peter piper picked a peck of pickled peppers. a peck of pickeled 
peppers peter piper picked. if piper piper picked a peck of pickeled 
peppers, wheres the peck of pickled peppers peter piper picked"

for i in range (0, len (strg)):
    if str[i] in ('.'):  
        count = count + 1;
    if str[i] in (','):  
        count2 = count2 + 1;
    if str[i] in ('?'):  
        count3 = count3 + 1;
    if str[i] in ('!'):  
        count4 = count4 + 1;


print ("Total number of full stops string: ");  
print (count);  

我希望输出:句号总数:x 但是目前它的输出是:

1 个答案:

答案 0 :(得分:2)

您不小心将'str'用作字符串名称而不是strg

count = count2 = count3 = count4 = 0

strg = '''peter piper picked a peck of pickled peppers. a peck of pickeled 
peppers peter piper picked. if piper piper picked a peck of pickeled 
peppers, wheres the peck of pickled peppers peter piper picked'''

for i in range (0, len (strg)):
    if strg[i] in ('.'):  
        count = count + 1;
    if strg[i] in (','):  
        count2 = count2 + 1;
    if strg[i] in ('?'):  
        count3 = count3 + 1;
    if strg[i] in ('!'):  
        count4 = count4 + 1;


print ("Total number of full stops string: ");  
print (count);