Using len for text but discarding spaces in the count

后端 未结 7 1307
天命终不由人
天命终不由人 2020-12-10 20:44

So, I am trying to create a program which counts the number of characters in a string which the user inputs, but I want to discard any spaces that the user enters.



        
7条回答
  •  抹茶落季
    2020-12-10 21:05

    I can propose a few versions.

    You can replace each space with an empty string and calculate the length:

    len(mystr.replace(" ", ""))
    

    You can calculate the length of the whole string and subtract the number of spaces:

    len(mystr) - mystr.count(' ')
    

    Or you can sum the lengths of all substrings after splitting the string with spaces:

    sum(map(len, mystr.split(' ')))
    

提交回复
热议问题