Home > OS >  Remove ".keyword" if it is present in particular element in list
Remove ".keyword" if it is present in particular element in list

Time:02-19

I am having list as below, in which one element contains "hostname.keyword". I want to remove ".keyword" from that element in the list.

I checked with below code but its not working.

search_columns=['service', 'perf', 'hostname.keyword']

if search_columns:
        if ".keyword" in search_columns:
            search_columns = search_columns.replace(".keyword","")
            print(search_columns)

Expected output-

search_columns=['service', 'perf', 'hostname']

Update-

Working code-

char = ".keyword"
for idx, ele in enumerate(search_columns):
    search_columns[idx] = ele.replace(char, '')

Ref link- https://www.geeksforgeeks.org/python-remove-given-character-from-strings-list/

CodePudding user response:

What about a simple list comprehension?

Assuming you want to remove trailing part:

search_columns=['service', 'perf', 'hostname.keyword']
query = '.keyword'

out = [e[:-len(query)] if e.endswith(query) else e
       for e in search_columns]

output: ['service', 'perf', 'hostname']

More generic code (remove in any place):

out = [e.replace(query, '') for e in search_columns]

CodePudding user response:

you idea is almost right, but you forgot to iterate in each element of your array before looking for the ".hostname". Try this:

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)
  • Related