我有如下串列,其中一個元素包含“hostname.keyword”。我想從串列中的那個元素中洗掉“.keyword”。
我檢查了下面的代碼,但它不起作用。
search_columns=['service', 'perf', 'hostname.keyword']
if search_columns:
if ".keyword" in search_columns:
search_columns = search_columns.replace(".keyword","")
print(search_columns)
預期產出-
search_columns=['service', 'perf', 'hostname']
更新-
作業代碼-
char = ".keyword"
for idx, ele in enumerate(search_columns):
search_columns[idx] = ele.replace(char, '')
參考鏈接- https://www.geeksforgeeks.org/python-remove-given-character-from-strings-list/
uj5u.com熱心網友回復:
一個簡單的串列理解怎么樣?
假設您要洗掉尾隨部分:
search_columns=['service', 'perf', 'hostname.keyword']
query = '.keyword'
out = [e[:-len(query)] if e.endswith(query) else e
for e in search_columns]
輸出:['service', 'perf', 'hostname']
更通用的代碼(在任何地方洗掉):
out = [e.replace(query, '') for e in search_columns]
uj5u.com熱心網友回復:
您的想法幾乎是正確的,但是在查找".hostname". 嘗試這個:
search_columns=['service', 'perf', 'hostname.keyword']
if search_columns:
for index, searchTerm in enumerate(search_columns):
if ".keyword" in searchTerm:
search_columns[index] = searchTerm.replace(".keyword","")
print(search_columns)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/427802.html
上一篇:Unity按鈕串列
