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() 函式將鍵的元素加入來形成一個字串。

  • 這被分配給一個變數。

  • 將字串和鍵進行比較,以檢視字串是否出現在上述列表中。

  • 該結果被分配給一個變數。

  • 根據該結果中的布林值,在控制檯上顯示相關訊息。

更新時間:2021-09-06

231 次瀏覽

開啟你的 職業 生涯

完成課程,獲得認證

開始
廣告