如何在 Python 字串中檢查空格?


在當今的 21 世紀,對於擁有大量資料的組織來說,處理資料是最具挑戰性的任務,並且隨著資料科學和機器學習的發展,資料訪問變得更加容易。空格也稱為字串字元之間的空白字元。空格沒有資料,或者它只是空的,並且在程式設計師編碼時會造成問題。因此,為了檢查字串中的空格,涉及多種方法,這裡解釋了一些方法。字串由字元組成,Python 語言屬於 OOPS 概念,它會立即執行程式碼而無需檢查錯誤。

如何在 Python 字串中檢查空格

在字串資料結構中,可以使用以下各種方法或方法來檢查空格:

方法

方法 1:使用 isspace() 方法

方法 2:使用正則表示式

方法 3:使用“in”運算子

方法 1:使用 isspace() 方法檢查字串中空格的 Python 程式

isspace() 方法檢查給定字串中的空白字元,並提及索引值以檢查空格。

演算法

  • 步驟 1 − 初始化名為 check_sent 的變數。

  • 步驟 2 − 字串在單詞之間包含空格,要檢查空格,使用 isspace() 方法。

  • 步驟 3 − 它根據索引值驗證該索引值處是否存在空格。

  • 步驟 4 − 索引值從 0 開始,在此程式碼中,索引值 7 被初始化以搜尋空格。

  • 步驟 5 − 如果存在空格,則返回“True”,否則返回“False”。

  • 步驟 6 − 基於空格,返回相應的語句。

示例

#initializing the string with a sentence and assigning it to a variable
check_sent = "Welcome to Tutorialspoint"
#isspace() method is used to check whether the space is found in index value of 7
if check_sent[7].isspace():
   #if true this statement is printed
	print("The string contains whitespaces")
else:
   #if false this statement is printed
	print("The string does not contain whitespaces")

輸出

The string contains whitespaces

方法 2:使用正則表示式檢查字串中空格的 Python 程式

演算法

  • 步驟 1 − 匯入 re 模組,並將輸入初始化為字串變數“ Welcome to Tutorialspoint”。

  • 步驟 2 − 字串在單詞之間包含空格,要檢查空格,使用 re.match() 方法。

  • 步驟 3 − 根據給定的索引值,它查詢該索引值處是否存在空格。

  • 步驟 4 − 索引值從 0 開始,在此程式碼中,索引值 7 被初始化以查詢空格。

  • 步驟 5 − 如果存在空格,則返回“True”,否則返回“False”。

  • 步驟 6 − 最後,列印指定的語句。

示例

#importing the re module
import re

# initializing the string with a sentence and assigning it to a variable
check_sent = "Welcome to Tutorialspoint"

# using regular expressions to check if there is whitespace at index 7
if re.match(r"\s", check_sent[7]):
   #if true this statement is printed
   print("The string contains whitespace")
else:
   #if false this statement is printed
   print("The string does not contain whitespace")

輸出

The string contains whitespaces

方法 3:使用“in”運算子檢查字串中空格的 Python 程式

宣告“in”運算子,並基於此宣告,在給定字串中檢查空格。

演算法

  • 步驟 1 − 初始化輸入字串並分配變數。

  • 步驟 2 − 字串在單詞之間包含空格,要檢查空格,使用“in”運算子。

  • 步驟 3 − 根據給定的索引值,它查詢該索引值處是否存在空格。

  • 步驟 4 − 索引值從 0 開始,在此程式碼中,索引值 7 被初始化以查詢空格。

  • 步驟 5 − 如果存在空格,則返回“True”,否則返回“False”。

  • 步驟 6 − 基於空格,返回相應的語句。

示例

# initializing the string with a sentence and assigning it to a variable
check_sent = "Welcome to Tutorialspoint"

# using the 'in' operator to check if there is whitespace at index 7
if ' ' in check_sent[7]:
   # if true this statement is printed
   print("The string contains whitespaces")
else:
   # if false this statement is printed
   print("The string does not contain whitespaces")

輸出

The string does not contain whitespaces

結論

Python 程式用於檢查給定資料結構中的空格或空白字元。要檢查 Python 字串中的空格,我們可以使用各種方法,例如“in”運算子、isspace() 以及正則表示式。刪除空格後,程式可以順利執行。

更新於: 2023 年 8 月 25 日

6K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.