RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
Python程序:计算字符串中总字数

创新互联Python教程:

成都创新互联长期为上1000+客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为原州企业提供专业的网站制作、网站设计,原州网站改版等技术服务。拥有十年丰富建站经验和众多成功案例,为您定制开发。

写一个 Python 程序来计算一个字符串中的总字数,并给出一个实例。

计算字符串中总字数的 Python 程序示例 1

这个 python 程序允许用户输入一个字符串(或字符数组)。接下来,它使用 For 循环计算该字符串中出现的单词总数。这里,我们使用 Python For 循环来迭代字符串中的每个字符。在 For 循环中,我们使用 If 语句来检查是否有空格。如果它找到了空白,那么总字数就会增加。

# Python program to Count Total Number of Words in a String

str1 = input("Please Enter your Own String : ")
total = 1

for i in range(len(str1)):
    if(str1[i] == ' ' or str1 == '\n' or str1 == '\t'):
        total = total + 1

print("Total Number of Words in this String = ", total)

计算字符串字数的 Python 程序示例 2

这个 python 程序的一个字符串的总字数同上。然而,我们只是将换成了而环。

# Python program to Count Total Number of Words in a String

str1 = input("Please Enter your Own String : ")
total = 1
i = 0

while(i < len(str1)):
    if(str1[i] == ' ' or str1 == '\n' or str1 == '\t'):
        total = total + 1
    i = i + 1

print("Total Number of Words in this String = ", total)

Python 使用 while 循环输出对字符串中的单词进行计数

Please Enter your Own String : Tutorial Gateway
Total Number of Words in this String =  2

计算字符串总字数的 Python 程序示例 3

该 Python 计数字符串中的总字数与第一个示例相同。但是,这一次,我们使用了函数概念来分离 Python 逻辑。

# Python program to Count Total Number of Words in a String

def Count_Total_Words(str1):
    total = 1
    for i in range(len(str1)):
        if(str1[i] == ' ' or str1 == '\n' or str1 == '\t'):
            total = total + 1
    return total

string = input("Please Enter your Own String : ")
leng = Count_Total_Words(string)
print("Total Number of Words in this String = ", leng)

Python 使用函数输出对字符串中的单词进行计数

Please Enter your Own String : Python Hello World Program
Total Number of Words in this String =  4

本文题目:Python程序:计算字符串中总字数
文章起源:http://www.jxjierui.cn/article/djjighe.html