Using len for text but discarding spaces in the count

后端 未结 7 1301
天命终不由人
天命终不由人 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 20:59

    You can also do

    sum(1 for c in s if c!=' ') 
    

    Which avoids any unnecessary temporary string or list.

    0 讨论(0)
  • 2020-12-10 21:00

    Use sum with a generator expression:

    >>> text = 'foo  bar  spam'
    >>> sum(len(x) for x in text.split())
    10
    

    Or str.translate with len:

    >>> from string import whitespace
    >>> len(text.translate(None, whitespace)) #Handles all types of whitespace characters
    10
    
    0 讨论(0)
  • 2020-12-10 21:01

    Why can't you just do:

    >>> mystr = input("Please enter in a full name: ")
    Please enter in a full name: iCodez wrote this
    >>> len(mystr.replace(" ", ""))
    15
    >>> len(mystr)
    17
    >>>
    

    This gets the length of the string minus the spaces.

    0 讨论(0)
  • 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(' ')))
    
    0 讨论(0)
  • 2020-12-10 21:06

    To count the number of characters excluding spaces, you can simply do:

    >>> full_name = "John DOE"
    >>> len(full_name) - full_name.count(' ')
    7
    
    0 讨论(0)
  • 2020-12-10 21:11

    Count the length and subtract the number of spaces:

    >>> full_name = input("Please enter in a full name: ")
    Please enter in a full name: john smith
    >>> len(full_name) - full_name.count(' ')
    9
    >>> len(full_name)
    
    0 讨论(0)
提交回复
热议问题