How do I make sure I count the correct number of words in a string if there are multiple spaces between words?How do I iterate over the words of a string?How do I check if a string is a number (float)?How do I return multiple values from a function?How would you count occurrences of a string (actually a char) within a string?How do I make the first letter of a string uppercase in JavaScript?Split Strings into words with multiple word boundary delimitersCount the number occurrences of a character in a stringIn YAML, how do I break a string over multiple lines?How do I check if a string contains a specific word?Is it a good practice to use try-except-else in Python?

Will Jimmy fall off his platform?

Why do Klingons use cloaking devices?

What is the highest level of accuracy in motion control a Victorian society could achieve?

Do intermediate subdomains need to exist?

Is kapton suitable for use as high voltage insulation?

How would a sea turtle end up on its back?

What causes a fastener to lock?

Why do most airliners have underwing engines, while business jets have rear-mounted engines?

Middle/Vertical alignment doesn't work with table of images

Convert Front Door Entry Mailbox to a Front & Rear Door Entry Mailbox

Is it possible to spoof an IP address to an exact number?

Would the Life cleric's Disciple of Life feature supercharge the Regenerate spell?

Advice for making/keeping shredded chicken moist?

Can a USB hub be used to access a drive from 2 devices?

What happens if the limit of 4 billion files was exceeded in an ext4 partition?

Is it bad to suddenly introduce another element to your fantasy world a good ways into the story?

Did Stalin kill all Soviet officers involved in the Winter War?

Are "confidant" and "confident" homophones?

How frequently do Russian people still refer to others by their patronymic (отчество)?

Is this car delivery via Ebay Motors on Craigslist a scam?

soda water first stored in refrigerator and then outside

Is it acceptable that I plot a time-series figure with years increasing from right to left?

Should I increase my 401(k) contributions, or increase my mortgage payments

What is the difference between an "empty interior" and a "hole" in topology?



How do I make sure I count the correct number of words in a string if there are multiple spaces between words?


How do I iterate over the words of a string?How do I check if a string is a number (float)?How do I return multiple values from a function?How would you count occurrences of a string (actually a char) within a string?How do I make the first letter of a string uppercase in JavaScript?Split Strings into words with multiple word boundary delimitersCount the number occurrences of a character in a stringIn YAML, how do I break a string over multiple lines?How do I check if a string contains a specific word?Is it a good practice to use try-except-else in Python?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am writing a function in Python 3 called word_count (that takes in a parameter, which I have called my_string) that is supposed to count the number of words in a string. The string might contain words with multiple space (e.g. hello there), and the function needs to be able to count that it is two words. I'm not supposed to use any built-in Python functions, and I am using try-except as well if I encounter any errors (e.g. if a value is interested that isn't a string, except will execute returning "Not a string"



I have been able to write a function, and I created a counter variable called numspaces, which I have initialized to 0. I then write try, then a for loop with an index variable called current_character that will run through all the current characters in my_string. I have written a conditional saying if current_character is equal to a space, numspaces needs to increment by one, and numwords (a variable I use to keep count of total number of words in a string) is equal to numspaces + 1. I then wrote an else if statement that say if numspaces equals 0, numwords = 1 and return numwords. If an error is encountered, I have written an except that returns "Not a string"



def word_count(my_string):
numspaces = 0
try:
for current_character in my_string:
if current_character == " ":
numspaces += 1
numwords = numspaces + 1
elif numspaces == 0:
numwords = 1
return numwords
except:
return "Not a string"


Below are some test cases, and expected results when using the test cases:



Word Count: 4
Word Count: 2
Word Count: Not a string
Word Count: Not a string
Word Count: Not a string

print("Word Count:", word_count("Four words are here!"))
print("Word Count:", word_count("Hi David"))
print("Word Count:", word_count(5))
print("Word Count:", word_count(5.1))
print("Word Count:", word_count(True))


When I run the code I have written, I get the following output:



Word Count: 4
Word Count: 4
Word Count: Not a string
Word Count: Not a string
Word Count: Not a string


I am not sure how to tweak my code to account for something like Test Case 2 ("Hi David")










share|improve this question






























    0















    I am writing a function in Python 3 called word_count (that takes in a parameter, which I have called my_string) that is supposed to count the number of words in a string. The string might contain words with multiple space (e.g. hello there), and the function needs to be able to count that it is two words. I'm not supposed to use any built-in Python functions, and I am using try-except as well if I encounter any errors (e.g. if a value is interested that isn't a string, except will execute returning "Not a string"



    I have been able to write a function, and I created a counter variable called numspaces, which I have initialized to 0. I then write try, then a for loop with an index variable called current_character that will run through all the current characters in my_string. I have written a conditional saying if current_character is equal to a space, numspaces needs to increment by one, and numwords (a variable I use to keep count of total number of words in a string) is equal to numspaces + 1. I then wrote an else if statement that say if numspaces equals 0, numwords = 1 and return numwords. If an error is encountered, I have written an except that returns "Not a string"



    def word_count(my_string):
    numspaces = 0
    try:
    for current_character in my_string:
    if current_character == " ":
    numspaces += 1
    numwords = numspaces + 1
    elif numspaces == 0:
    numwords = 1
    return numwords
    except:
    return "Not a string"


    Below are some test cases, and expected results when using the test cases:



    Word Count: 4
    Word Count: 2
    Word Count: Not a string
    Word Count: Not a string
    Word Count: Not a string

    print("Word Count:", word_count("Four words are here!"))
    print("Word Count:", word_count("Hi David"))
    print("Word Count:", word_count(5))
    print("Word Count:", word_count(5.1))
    print("Word Count:", word_count(True))


    When I run the code I have written, I get the following output:



    Word Count: 4
    Word Count: 4
    Word Count: Not a string
    Word Count: Not a string
    Word Count: Not a string


    I am not sure how to tweak my code to account for something like Test Case 2 ("Hi David")










    share|improve this question


























      0












      0








      0








      I am writing a function in Python 3 called word_count (that takes in a parameter, which I have called my_string) that is supposed to count the number of words in a string. The string might contain words with multiple space (e.g. hello there), and the function needs to be able to count that it is two words. I'm not supposed to use any built-in Python functions, and I am using try-except as well if I encounter any errors (e.g. if a value is interested that isn't a string, except will execute returning "Not a string"



      I have been able to write a function, and I created a counter variable called numspaces, which I have initialized to 0. I then write try, then a for loop with an index variable called current_character that will run through all the current characters in my_string. I have written a conditional saying if current_character is equal to a space, numspaces needs to increment by one, and numwords (a variable I use to keep count of total number of words in a string) is equal to numspaces + 1. I then wrote an else if statement that say if numspaces equals 0, numwords = 1 and return numwords. If an error is encountered, I have written an except that returns "Not a string"



      def word_count(my_string):
      numspaces = 0
      try:
      for current_character in my_string:
      if current_character == " ":
      numspaces += 1
      numwords = numspaces + 1
      elif numspaces == 0:
      numwords = 1
      return numwords
      except:
      return "Not a string"


      Below are some test cases, and expected results when using the test cases:



      Word Count: 4
      Word Count: 2
      Word Count: Not a string
      Word Count: Not a string
      Word Count: Not a string

      print("Word Count:", word_count("Four words are here!"))
      print("Word Count:", word_count("Hi David"))
      print("Word Count:", word_count(5))
      print("Word Count:", word_count(5.1))
      print("Word Count:", word_count(True))


      When I run the code I have written, I get the following output:



      Word Count: 4
      Word Count: 4
      Word Count: Not a string
      Word Count: Not a string
      Word Count: Not a string


      I am not sure how to tweak my code to account for something like Test Case 2 ("Hi David")










      share|improve this question
















      I am writing a function in Python 3 called word_count (that takes in a parameter, which I have called my_string) that is supposed to count the number of words in a string. The string might contain words with multiple space (e.g. hello there), and the function needs to be able to count that it is two words. I'm not supposed to use any built-in Python functions, and I am using try-except as well if I encounter any errors (e.g. if a value is interested that isn't a string, except will execute returning "Not a string"



      I have been able to write a function, and I created a counter variable called numspaces, which I have initialized to 0. I then write try, then a for loop with an index variable called current_character that will run through all the current characters in my_string. I have written a conditional saying if current_character is equal to a space, numspaces needs to increment by one, and numwords (a variable I use to keep count of total number of words in a string) is equal to numspaces + 1. I then wrote an else if statement that say if numspaces equals 0, numwords = 1 and return numwords. If an error is encountered, I have written an except that returns "Not a string"



      def word_count(my_string):
      numspaces = 0
      try:
      for current_character in my_string:
      if current_character == " ":
      numspaces += 1
      numwords = numspaces + 1
      elif numspaces == 0:
      numwords = 1
      return numwords
      except:
      return "Not a string"


      Below are some test cases, and expected results when using the test cases:



      Word Count: 4
      Word Count: 2
      Word Count: Not a string
      Word Count: Not a string
      Word Count: Not a string

      print("Word Count:", word_count("Four words are here!"))
      print("Word Count:", word_count("Hi David"))
      print("Word Count:", word_count(5))
      print("Word Count:", word_count(5.1))
      print("Word Count:", word_count(True))


      When I run the code I have written, I get the following output:



      Word Count: 4
      Word Count: 4
      Word Count: Not a string
      Word Count: Not a string
      Word Count: Not a string


      I am not sure how to tweak my code to account for something like Test Case 2 ("Hi David")







      python string function for-loop try-catch






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 25 at 20:01







      Ravi

















      asked Mar 25 at 19:50









      RaviRavi

      307 bronze badges




      307 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          0














          There are at least two options:



          1. Replace all double spaces, until you have only single spaces before you start counting

          2. Keep track, what the previous character was and add extra conditions





          share|improve this answer






















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55345402%2fhow-do-i-make-sure-i-count-the-correct-number-of-words-in-a-string-if-there-are%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            There are at least two options:



            1. Replace all double spaces, until you have only single spaces before you start counting

            2. Keep track, what the previous character was and add extra conditions





            share|improve this answer



























              0














              There are at least two options:



              1. Replace all double spaces, until you have only single spaces before you start counting

              2. Keep track, what the previous character was and add extra conditions





              share|improve this answer

























                0












                0








                0







                There are at least two options:



                1. Replace all double spaces, until you have only single spaces before you start counting

                2. Keep track, what the previous character was and add extra conditions





                share|improve this answer













                There are at least two options:



                1. Replace all double spaces, until you have only single spaces before you start counting

                2. Keep track, what the previous character was and add extra conditions






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 25 at 20:02









                Uli SotschokUli Sotschok

                6953 silver badges14 bronze badges




                6953 silver badges14 bronze badges


















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55345402%2fhow-do-i-make-sure-i-count-the-correct-number-of-words-in-a-string-if-there-are%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현