Python –在 ASCII 範圍內過濾字串


當需要過濾 ASCII 範圍內的字串時,可以使用表示 Unicode 的“ord”方法和“all”運算子。

以下是該方法的演示 −

示例

 線上演示

my_string = "Hope you are well"

print("The string is :")
print(my_string)

my_result = all(ord(c) < 128 for c in my_string)

if(my_result == True):
   print("The string contains ASCII characters")
else:
   print("The string doesn't contain all ASCII characters")

輸出

The string is :
Hope you are well
The string contains ASCII characters

說明

  • 定義一個字串並顯示在控制檯上。

  • 在字串中的每個字母上呼叫“ord”方法,並檢查其 Unicode 值是否小於 128。

  • 如果所有元素的 Unicode 表示都小於 128,則分配一個布林“True”值。

  • 迭代完成後,檢查此布林值。

  • 基於此值,在控制檯上顯示相關訊息。

更新於: 2021 年 9 月 4 日

264 次瀏覽

啟動您的職業生涯

完成課程並獲得認證

開始
廣告