Python – 從字串列表獲取子字串的所有出現情況
當需要從字串列表獲取子字串的所有出現情況時,會使用簡單的列表解析和“startswith”方法。
示例
以下是對 Same 進行說明:
my_string = "Is python fun to learn?"
print("The list is :")
print(my_string)
substring = "pyt"
print("The substring is :")
print(substring)
my_result = [i for i in range(len(my_string)) if my_string.startswith(substring, i)]
print("The result is :")
print(my_result)輸出
The list is : Is python fun to learn? The substring is : pyt The result is : [3]
說明
定義了一個字串並顯示在控制檯上。
定義了另一個子字串並顯示在控制檯上。
使用列表解析以迭代字串。
使用“startswith”方法以檢查字串是否以特定模式/子字串開頭。
如果是,則在轉換為列表後,將其新增到變數中。
這將顯示在控制檯輸出中。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP