如何在 Python 中檢查字串是否為 ASCII 字串?


ASCII 代表美國資訊交換標準程式碼。ASCII 是一種字元編碼系統,它為標準鍵盤上的每個字母、數字和符號分配一個唯一的數字。在 Python 中,每個字元都基於 ASCII 程式碼具有一個數值,可以使用 ord() 函式進行檢查。在處理基於文字的資料以及編碼或解碼文字時,瞭解 ASCII 非常重要。

要檢查 Python 中的字串是否為 ASCII 字串,可以使用 Python 中內建的字串模組。

以下是一些檢查字串是否為 ASCII 字串的方法

使用 isascii() 方法

示例

在此示例中,isascii() 方法檢查字串中的所有字元是否為 ASCII 字元。如果字串中的所有字元都是 ASCII 字元,則該方法返回 True,並且該字串被認為是 ASCII 字串。

my_string = "lorem ipsum"
if my_string.isascii():
    print("The string is in ASCII")
else:
    print("The string is not in ASCII")

輸出

The string is in ASCII

使用正則表示式

示例

在此示例中,正則表示式 ^[\x00-\x7F]+$ 匹配僅包含 ASCII 字元的任何字串。如果正則表示式與字串匹配,則該字串為 ASCII 字串。

import re
my_string = "lorem ipsum"

if re.match("^[\x00-\x7F]+$", my_string):
    print("The string is in ASCII")
else:
    print("The string is not in ASCII")

輸出

The string is in ASCII

使用 ord() 函式

示例

在此示例中,ord() 函式用於獲取字串中每個字元的 ASCII 值。如果所有 ASCII 值都小於 128,則該字串為 ASCII 字串。

my_string = "lorem ipsum"
is_ascii = all(ord(c) < 128 for c in my_string)
if is_ascii:
    print("The string is in ASCII")
else:
    print("The string is not in ASCII")

輸出

The string is in ASCII

可以使用任何這些方法來檢查字串是否為 ASCII 字串。

以下是在 Python 中檢查字串是否為 ASCII 字串的另外兩個程式碼示例

示例

此程式碼示例使用 all() 函式和列表推導式來檢查字串中的所有字元的 ASCII 值是否都小於 128。如果所有字元都滿足此條件,則該字串被認為是 ASCII 字串。

string1 = "lorem ipsum"

if all(ord(c) < 128 for c in string1):
    print("The string is in ASCII.")

else:
    print("The string is not in ASCII.")

輸出

The string is in ASCII.

示例

此程式碼示例定義了一個函式 is_ascii(),該函式檢查字串中的所有字元是否為可列印的 ASCII 字元。該函式使用 string.printable 常量,其中包含所有可列印的 ASCII 字元。如果字串中的所有字元都是可列印的 ASCII 字元,則該函式返回 True,並且該字串被認為是 ASCII 字串。

import string
def is_ascii(s):
    return all(c in string.printable for c in s)
string1 = "lorem ipsum"
if is_ascii(string1):
    print("The string is in ASCII.")
else:
    print("The string is not in ASCII.")

輸出

The string is in ASCII.

更新於: 2023年8月10日

1K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.