Count input length without spaces, periods, or commas

Question:

How do you count the length of a string (example “Hello, Mr. John. Have a good day.” taking out the commas, periods and white spaces?

string = "Hello, Mr. John. Have a good day."
print(len(string))

The count should be 23. I’m coming up with 33 with the commas, periods and white spaces.

Asked By: Macro

||

Answers:

print(len(string.replace(",", "").replace(".", "").replace(" ","")))
Answered By: yixi zhou

I would recommend a regular expression here. That way you don’t need to do multiple str.replace.

In [8]: import re                                                               

In [9]: string = "Hello, Mr. John. Have a good day."                                     

In [10]: new_str = re.sub('[ .,]', '', string)                                  

In [11]: len(new_str)                                                           
Out[11]: 23

Here the replacement group is [ .,]. Anything within the brackets will be replaced, which in this case is a space, period or comma.

Answered By: Chrispresso

Whitespace can be more than just space characters so use s:

import re
string = "Hello, Mr. John. Have a good day."
print(len(re.sub(r'[,.s]+', '', string)))

23

Answered By: Booboo

The @yixizhou answer is simple and accurately a good one but if you want to avoid the other thing you can use regular expression for correct length like this

import re
string = "Hello, Mr. John. Have a good day."
print(len("".join(re.findall(r'[A-Z0-9a-z]', string))) ) 
Answered By: Amin MG
#include <iostream>
#include <string>
using namespace std;

int main() {
   string userText;
   int i = 0;
   string str1;
   string str2="";
   
   getline(cin, userText);  // Gets entire line, including spaces. 

   while(i<userText.size()){
      if(userText.at(i) != ' ' && userText.at(i) !=',' && userText.at(i) !='.'){
         str1 = userText.at(i);
         str2 = str2 + str1;
      }
   ++i;
   }
   cout << str2.size()<<endl;
      

   return 0;
}
Answered By: Ali Ahmad
user_text = input()
numOfChars = 0 #number of charachters
count = 0 #to count index of user_text
for i in user_text:
    if user_text[count] != ' ' and user_text[count] != '.' and user_text[count] != ',':
        numOfChars += 1
    count += 1
print(numOfChars)
user_text = input()

comma_count = 0
period_count = 0
space_count = 0
for char in user_text:
    initial_len = len(user_text)
    if char == ',':
        comma_count += 1
    elif char == '.':
        period_count += 1
    elif char == ' ':
        space_count += 1
not_allowed = (comma_count + period_count + space_count)
print(initial_len - not_allowed)

My newbie solution for this problem sets up a for loop to assess each character of input and total string length. Each character is compared to unwanted character types, counting them individually.

Answered By: Smallfry
user_text = input()
count = 0 
for char in user_text:
if not(char in " .,"):
    count += 1 
print(count)
Answered By: tresa

Similar to @Tresa, but see proper edits/indents below, accompanied by further explanation:

user_text = input()
output = 0  #set variable

for char in user_text:  #similar to ZyBooks lesson 4.9
    if not(char in " .,"):  #not similar to the lesson
        output += 1 
print(output)

We are going to forego the if statements and do an if not statement, which will clean up your code and make it use as few lines as possible — thus making it more efficient.

You may be able to do something similar to @Booboo, but DO NOT follow the top program by @Amin MG / @ eyllanesc. The program only accounts for letters and numbers, and not other special characters — the instructions are only to remove the commas, periods, and white spaces. That means, if a test has "Howdy!", the program will not properly account for the ‘!’, thus yielding a failed test.

Answered By: ObscuredData

There are some creative and unique approaches to solving this lab. Instead of using the replace() feature, I opted to use a tuple, a counter, and a membership operator:

user_input = input()

char_count = 0

for value in user_input:
    if value not in (' ', '.', ','):
        char_count += 1
print(char_count)
Answered By: John B.

Here’s another option

user_text = input()

''' Type your code here. '''
user_text = user_text.replace(' ','')
user_text = user_text.replace('.','')
user_text = user_text.replace('!','')
user_text = user_text.replace(',','')

print(len(user_text))
Answered By: Joseph M
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.