Python 程序,用于计算字符串中存在的单词数量和字符数量


当需要计算字符串中存在的单词数量和字符数量时,

以下是对此的演示

示例

 即时演示

my_string = "Hi there, how are you Will ? "
print("The string is :")
print(my_string)
my_chars=0
my_words=1
for i in my_string:
   my_chars=my_chars+1
   if(i==' '):
      my_words=my_words+1
print("The number of words in the string are :")
print(my_words)
print("The number of characters in the string are :")
print(my_chars)

输出

The string is :
Hi there, how are you Will ?
The number of words in the string are :
8
The number of characters in the string are :
29

说明

  • 定义一个字符串,并将其显示在控制台上。

  • 将字符数分配为 0。

  • 将单词数分配为 1。

  • 迭代字符串,并递增字符变量。

  • 如果遇到空格,则单词数也递增。

  • 这些值显示在控制台上。

更新于:16-4-2021

1K+ 次浏览

启动您的 职业生涯

通过完成课程获取认证

开始学习
广告
© . All rights reserved.