python怎么统计字符数量

17次阅读
没有评论

共计 479 个字符,预计需要花费 2 分钟才能阅读完成。

要统计字符数量, 可以使用 Python 中的 count() 方法。例如:

string = "hello world"
char = 'o'
count = string.count(char)
print(f"The character '{char}' appears {count} times in the string.")

这段代码将输出:

The character 'o' appears 2 times in the string.

如果你想统计字符串中所有不重复字符的数量,你可以使用 set() 函数来获取字符串中唯一字符的集合,然后再计算每个字符在原始字符串中出现的次数。例如:

string = "hello world"
unique_chars = set(string)
char_count = {}

for char in unique_chars:
    count = string.count(char)
    char_count[char] = count

print(char_count)

这段代码将输出一个字典,其中包含字符串中每个不重复字符及其出现的次数。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-05-15发表,共计479字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)