Skip to content
Advertisement

Count input length without spaces, periods, or commas

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.

Advertisement

Answer

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))) ) 
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement