共計 479 個字符,預(yù)計需要花費(fèi) 2 分鐘才能閱讀完成。
要統(tǒng)計字符數(shù)量, 可以使用 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.
如果你想統(tǒng)計字符串中所有不重復(fù)字符的數(shù)量,你可以使用 set()
函數(shù)來獲取字符串中唯一字符的集合,然后再計算每個字符在原始字符串中出現(xiàn)的次數(shù)。例如:
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)
這段代碼將輸出一個字典,其中包含字符串中每個不重復(fù)字符及其出現(xiàn)的次數(shù)。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完