Python – 在字元列表中測試字串及其逆向操作
如果需要在字元列表中測試字串以及相反的操作,可以使用簡單的“in”運算子和“join”方法。
下面是對其進行的演示 −
示例
my_string = 'python'
print("The string is :")
print(my_string)
my_key = ['p', 'y', 't', 'h', 'o', 'n', 't', 'e', 's', 't']
print("The key is ")
print(my_key)
joined_list = ''.join(my_key)
my_result = my_string in joined_list
print("The result is :")
if(my_result == True):
print("The string is present in the character list")
else:
print("The string is not present in the character list")輸出
The string is : python The key is ['p', 'y', 't', 'h', 'o', 'n', 't', 'e', 's', 't'] The result is : The string is present in the character list
說明
定義並顯示一個字串在控制檯上。
在控制檯上定義並顯示鍵的值。
使用 .join() 函式將鍵的元素加入來形成一個字串。
這被分配給一個變數。
將字串和鍵進行比較,以檢視字串是否出現在上述列表中。
該結果被分配給一個變數。
根據該結果中的布林值,在控制檯上顯示相關訊息。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP