如何在Python列表中檢查空格?
Python語言包含各種各樣的資料結構,本文將討論列表資料結構。在列表中,元素按某種順序排列,可以使用各種方法來檢查空格。列表中的元素可以是字串或空字串,也可以是字串中的製表符或任何空格。在下面給出的各種方法中,isspace()函式被認為是比較容易的一種。
方法
方法一 - 使用“re”模組
方法二 - 使用迭代方法
方法三 - 使用isspace()方法
方法一:使用re.compiler()方法對輸入資料進行分類的Python程式
匯入re模組以使用re.compiler()函式將空格與給定列表的正則表示式匹配。
演算法
步驟1 - 匯入“re”模組以使用正則表示式。
步驟2 - 宣告輸入列表,其中元素包含字串和空格。
步驟3 - 在列表資料結構中,使用re.compile()方法將空格與正則表示式匹配。
步驟4 - 結合迭代過程,模式搜尋函式將遍歷值列表。
步驟5 - 當空格不正確時,它返回“不包含空格”。
示例
#”re” library is imported
import re
#defining the list with strings along with whitespace
my_list = ['hello', 'world ', ' ', '\t']
pattern = re.compile(r'\s+')
for val in my_list:
if pattern.search(val):
print(f"'{val}' contains whitespace")
else:
print(f"'{val}' does not contain whitespace")
輸出
'hello' does not contain whitespace 'world ' contains whitespace ' ' contains whitespace ' ' contains whitespace
方法二:使用迭代方法對輸入資料進行分類的Python程式
for迴圈將遍歷列表以及split()和join()函式。
演算法
步驟1 - 在輸入列表中初始化包含字串的元素,例如“Welcome”、“to”和“Tutorialspoint”。
步驟2 - 列表資料結構中的split()方法用於將給定的字串分割成字元。
步驟3 - 然後使用join()函式連線沒有任何空格的字串。
步驟4 - 列印沒有任何空格的字串語句。
示例
#initializing the list with strings along with whitespace
list_1 = ['Welcome','to','Tutorialspoint']
#defining the empty list
new_list = []
#for loop is used to iterate through the given list
for space in list_1:
# split() function is used to split the string
words = space.split()
# joining the strings without too many spaces and using only single space
new_space = ' '.join(words)
# add the cleaned string to the new list
new_list.append(new_space)
if new_list != list_1:
#returning the statement in the list
print("yes, it contains whitespace")
else:
print("no, it does not whitespace")
輸出
no, it does not whitespace
方法三:使用isspace()方法對輸入資料進行分類的Python程式
用於檢查給定字串列表中空格的方法是isspace()函式。
演算法
步驟1 - 使用包含字串的元素初始化輸入列表。
步驟2 - 列表資料結構中的isspace()方法用於確定是否可以訪問任何空格,並且一旦刪除了任何額外的空格,就會生成新的列表。
步驟3 - if語句用於在任何索引值處提及字串“Welcome to Tutorialspoint”時查詢空格。
步驟4 - 如果單詞之間的空格只有空格,則此方法返回true。
步驟5 - 列印沒有任何空格的字串語句。
示例
# The List data structure is initialized with Whitespaces
sen = "Welcome to Tutorialspoint"
# Using the isspace() method to check for whitespaces in the list
if sen[7].isspace():
#returning the statement in the list
print("yes, it contains whitespace")
else:
print("no, it does not whitespace")
輸出
yes, it contains whitespace
結論
Python程式用於檢查給定列表資料結構中的空格。空格可以以多種方式出現,例如製表符、空格甚至“\n”(換行符)。在運行復雜的程式時,如果發現空格,則必須將其刪除才能有效執行程式碼。
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP