Python Forum
Counting number of characters in a string - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Counting number of characters in a string (/thread-12260.html)



Counting number of characters in a string - Drone4four - Aug-16-2018

I’m trying to count the number of words that exist in the last line of a small text file.

Here is my text file:
Quote:Welcome to your First Tribulation Recruit.
Only the best recruits can become agents.
Do you have what it takes?
We will test your knowledge with this field readiness tribulation.
It should be pretty simple, since you only know the basics so far.
Let's get started.
Best of luck recruit.

Here is my code:
with open('field.txt') as field_variable:
    field_variable = field_variable.readlines() 
    list(field_variable)
    last = field_variable[-1] 
    num_chars = last.count(substring, start=0,end=-1) 
    print(num_chars)
Here is my expected output:
Quote:4

What I actually get is a traceback:
Quote:---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-21-5069a38ae83b> in <module>()
3 list(field_variable)
4 last = field_variable[-1]
----> 5 num_chars = last.count(substring, start=0,end=-1)
6 print(num_chars)

NameError: name 'substring' is not defined

As the traceback indicates, the issue is the form of my count method. It requires a substring as an argument. On Google I found a few tutorials (one, two) on Python’s count method which I learned is typically used to count the number of instances of a word or phrase inside a given string. I have my string declared but I do not wish to count the times a certain word appears inside it. Instead I wish to count the number of words for the whole line. As you can see at line 5 in my code, it says ‘substring’ not defined. If I remove the undeclared substring parameter, I then get this:
Quote:TypeError: count() takes no keyword arguments
What should my first keyword argument be in my count method to determine and then print the number of words in the last line of my text file?


RE: Counting number of characters in a string - ichabod801 - Aug-16-2018

The count method returns the number of times a specific string exists in another string. You have to give it the string to count. For example, "Craig Ichabod O'Brien".count('a') is equal to 2.

If you want to count the number of words in a line, use the split method. That will split the text into a list of words (words being text with no white space). The len of that list will be the number of words.