

You can always try them out to improve your string handling in Python. That said, there are many other ways of manipulating strings in addition to splitting. So instead of writing long blocks of code, it's always helpful to try out more efficient, simpler, and faster built-in methods of solving various coding problems. There are many other built-in functions in Python like this that simplify complex operations quickly and efficiently. You can even solve other problems with it as you desire. The split() function is a valuable Python tool, and as you've seen, you can use it to count the words in a file. Otherwise, it gives you the wrong output. Additionally, enforce the word count by leaving a space between the empty quotes in the parentheses. To make the for loop read each word separately, you should insert your file into a separate list as we did in the above code.
Python split how to#
Related: How to Open, Read, and Write to a File in Python Print(countWords( ''))Īlthough it's a little tricky, you can also do this using the for loop only: def countWords (file): Then split the text first and execute a count by returning the length of the resulting split using the built-in len() function: def countWords (file): But here, you need to open and read the file containing the text. Modify the code above to count the words in a separate file.

MyTexts = 'How to split a text in Python'
