查找字符串中最短单词总数的Python代码

2024-05-04 20:17:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在搜索一个python代码,它可以找到字符串中最短单词的总数。 例如,如果字符串是“这出戏是我抓住国王良知的东西”,那么结果应该是“8个简短的单词”


Tags: 字符串代码单词总数国王良知
1条回答
网友
1楼 · 发布于 2024-05-04 20:17:48

input_string = "The play 's the thing wherein I'll catch the conscience of the king."

计算字数:
print(len(input_string.split()))

输出:
13

数三个字母以内的单词数:
print(len([x for x in input_string.split() if len(x) <= 3]))

输出:
6

如果只需要三个字母或更少的单词列表,请排除len()函数。
print([x for x in input_string.split() if len(x) <= 3])

输出:
['The', "'s", 'the', 'the', 'of', 'the']

相关问题 更多 >