Python 字串字元計數程式


Python 中的字串可以包含任何字元序列,包括字母、數字、符號和空格。它可以表示文字、數字或任何其他可以表示為字元序列的資料型別。

在 Python 中,字串用單引號 ('') 或雙引號 ("") 括起來。多行字串可以使用三引號 (''' 或 """) 建立。以下是一些有效的 Python 字串示例

  • "Hello, World!"

  • "12345"

  • "Python is awesome!"

計算字串中字元的數量包括確定字串中單個字元的總數。Python 提供了各種字元計數技術:

  • 字串長度 - 最簡單的方法是使用大多數程式語言中提供的長度函式。它返回字串中字元的總數。

  • 迭代 - 另一種方法是迭代字串中的每個字元,併為遇到的每個非空格字元遞增計數器。此方法允許在計數時對每個字元執行其他操作或檢查。

  • 正則表示式 - 正則表示式提供強大的模式匹配功能。它們可用於識別和計算字串中特定型別的字元或模式。

在本文中,我們將討論上述計算字串中字元數量的技術。

使用 len() 函式

在這種方法中,我們將使用 Python 內建的 len() 函式來返回字串中字元的總數。

示例

這是一個使用 len() 函式計算字串中字元數量的示例。

# Define the input string
input_string = "***Tutorialspoint!***"
print("Input string:", input_string)

# Count the characters using len() function
character_count = len(input_string)
print("Number of characters:", character_count)

輸出

Input string: ***Tutorialspoint!***
Number of characters: 21

示例

在此示例中,我們將僅使用 len() 和 isalpha() 函式計算字母字元。

# Define the input string
input_string = "***Tutorialspoint!***"
print("Input string:", input_string)

# Count only alphabet characters using len() and isalpha() functions
character_count = len([character for character in input_string if character.isalpha()])
print("Number of characters:", character_count)

輸出

Input string: ***Tutorialspoint!***
Number of characters: 14

使用迴圈

在這種方法中,我們將首先初始化一個計數變數來跟蹤字元的數量。接下來,我們將遍歷字串中的每個字元。在迭代過程中,如果字元被識別為字母,我們將計數增加 1。

示例

在這裡,我們將僅使用 isalpha() 方法計算字母。

def count_characters(string):
    count = 0
    for char in string:
        if char.isalpha():
            count += 1
    return count

# Define the input string
input_string = "***Hello, World!***"
print("Input string:", input_string)

result = count_characters(input_string)
print("Number of characters:", result)

輸出

Input string: ***Hello, World!***
Number of characters: 10

使用正則表示式

re.findall() 函式用於計算輸入字串中字元的數量。正則表示式模式 r'\S' 匹配任何非空格字元。

示例

這是一個使用正則表示式計算輸入字串中字元數量的示例。

import re

# Define the input string
input_string = "***Hello, World!***"
print("Input string:", input_string)

# Count characters using re.findall() function
character_count = len(re.findall(r'\S', input_string))
print("Number of characters:", character_count)

輸出

Input string: ***Hello, World!***
Number of characters: 18

要僅計算字母字元,應使用正則表示式模式 r'[A-Za-z]'。

更新於:2023年8月29日

5K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告