溫馨提示×

python怎么統計字符數量

小億
159
2024-05-14 10:27:13
欄目: 編程語言

要統計字符數量, 可以使用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)

這段代碼將輸出一個字典,其中包含字符串中每個不重復字符及其出現的次數。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女