textString

need help to have the code fixed to tell me the amount of O,S,P letter in the textString
the code is as follow

textString="python is a general-purpose, high level programing language. It emphasizes code readability, and allows\
programmers to write applications in fewer lines of code than would be possible in other languages such as C."
oCount=0
sCount=0
pCount=0
for index in range(len(textString)):
    if textString[index]=='o':
        oCount=oCount+1
    if textString[index]=='s':
        sCount=sCount+1
    if textString[index]=='p':
        pCount=pCount+1
print("there are oCount 'o' characters")
print("there are sCount 's' characters")
print("there are pCount 'p' characters")
print("there are", len(textString), 'characters in the textString')

you want to print the oCount variable, not string oCount (yes, string and variable can have the same name)

so you can do something like:

print("there are {} 'o' characters".format(oCount))

also, why use range() in for loop? without range, you get the values from the string directly, so you don’t have to access the list by index each time

3 Likes

I use range because my teacher instructed me to use range she gave us the first half of the code and we just had to write the for and the print statements but I get no variable for print

1 Like

well, currently you only print a string, to print a string and a variable, there are several ways. string concatenation with +, string concatenation with , using %d placeholder or the use of format (which i showed in my previous answer)

So if the teacher tells you to jump in the river, you jump? I might hope not

Using range here is pretty pointless, without range:

for letter in textString:
    if letter == 'o':

your code is shorter and more readable. Furthermore, using if, elif and elif would save some condition checking (vs the 3 times if you use now)

4 Likes

We were told to not do a if-else loop just tonight to get the variable printed

1 Like

well, i suggested 4 possible ways you could print the variable, of 1 method i even posted the code, so you should be able to solve it now

3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.