+ 2

Q about .count() python

Hello we have simple code for counting symbols inside string. s = input() count = s.count(f) print(count) Q. Why i cant put this inside print(). Like. s = input() print(s.count(f)) Why second code end with error? We can make math inside print why can't use methods?

14th Jan 2024, 3:03 PM
Alexandr Meskin
Alexandr Meskin - avatar
6 Answers
+ 4
Q about what "f" is. i did not get an error. link your code.
14th Jan 2024, 3:27 PM
Lisa
Lisa - avatar
+ 4
You need to either define f in a variable, or if you are looking for the letter f in your string it must be enclosed in quotes: print(s.count("f"))
14th Jan 2024, 5:12 PM
StuartH
StuartH - avatar
+ 4
Alexandr Meskin , what did you mean by saying `symbols` to count? >>> is it punctuation like `!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~` ? in this case we can count anything except *alphanumericals* and *spaces*, because this is more efficient than counting for each of the symbols using a for loop: for char in text:text = 'a34Z& eK9$.;5 xx' # has 4 symbols counter = 0 for char in text: if not (char.isalnum() or char.isspace()): counter += 1 print(counter)
14th Jan 2024, 7:51 PM
Lothar
Lothar - avatar
+ 3
where did the “f” come from?
14th Jan 2024, 3:32 PM
Junior
Junior - avatar
+ 2
We can do whatever we want inside the print function. Its not about it.
14th Jan 2024, 3:42 PM
Toni Isotalo
Toni Isotalo - avatar
+ 1
As mang have pointed out here, what do you exactly refer “f” to? Liek what is the context? Provide full code.
15th Jan 2024, 11:55 AM
Hunter
Hunter - avatar