计算输入长度,不包含空格,句号或逗号

时间:2019-07-27 23:38:49

标签: python python-3.x

您如何计算字符串的长度(例如,“您好,约翰先生。祝您愉快。”去掉逗号,句点和空格?

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

计数应该是23。我要用逗号,句号和空格来得出33。

6 个答案:

答案 0 :(得分:1)

我会在这里推荐一个正则表达式。这样一来,您无需执行多个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

此处替换组为[ .,]。括号内的所有内容都将被替换,在这种情况下为空格,句点或逗号。

答案 1 :(得分:1)

空格不能只是空格字符,因此请使用 \ s

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

23

答案 2 :(得分:0)

print(len(string.replace(",", "").replace(".", "").replace(" ","")))

答案 3 :(得分:0)

@yixizhou答案简单而准确,是一个很好的答案,但是如果您想避免另一件事,则可以使用正则表达式来表示正确的长度

import re
string = "Hello, Mr. John. Have a good day."
print(len("".join(re.findall(r'[A-Z0-9a-z]', string))) ) 

答案 4 :(得分:0)

#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;
}

答案 5 :(得分:0)

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)