Python - 檢查分隔符是否相等
如果需要檢查字串的分隔符是否相等,則使用“len”方法、“list”方法和“set”運算子以及“if”條件。
示例
以下是演示:
my_string = '96%96%96%96%96%96' print("The string is : " ) print(my_string) my_split_char = "%" print("The character on which the string should be split is :") print(my_split_char) my_result = len(list(set(my_string.split(my_split_char)))) == 1 print("The resultant list is : ") if(my_result == True): print("All the splits are equal") else: print("All the splits are not equal")
輸出
The string is : 96%96%96%96%96%96 The character on which the string should be split is : % The resultant list is : All the splits are equal
解釋
定義了一個字串並顯示在控制檯上。
定義了字串應按其進行分割的字元。
它也顯示在控制檯上。
字串按此字元進行分割,並轉換為一個集合以獲取唯一元素。
它被轉換為一個列表。
檢查它是否長度為 1。
如果是,則此布林值儲存在一個變數中。
根據該布林變數的值,在控制檯上顯示相關訊息。
廣告