Replace whole word Python (only variable)

2019-09-10 23:34发布

问题:

I am trying to do a code which replace only whole word in string variable.First of all I found re.sub solution but there was no mentioned about variable inside. Now my solution looks (it does not replace whole word):

for index in (range(len(lista)):
    query=query.replace(lista[index],var)

As on example above, I want to replace value in lista[index] with value from VAR -> variable.

EDIT:

Example query:

Select Information,AdditionalInformation,Price from Table

example lista vales:

Information, Price 

example var:

var = "hide"

Finally query should looks:

Select hide,AdditionalInformation,hide from Table

回答1:

I think this should work:

for word in alist:
    query = re.sub(r'\b'+word+r'\b',var,query)


回答2:

You can compile a regex that matches any of the words in lista.

import re

query = "Select Information,AdditionalInformation,Price from Table"
lista = ["Information", "Price"]
var = "hide"

pat = re.compile(r'\b' + '|'.join(lista) + r'\b')
query = pat.sub(var, query)
print(query)

output

Select hide,AdditionalInformation,hide from Table

The \b is used to match word boundaries; this prevents "AdditionalInformation" from being modified. See Regular Expression Syntax in the docs. We need to write it as a raw string, r'\b', otherwise it gets interpreted as the ANSI escape code for backspace.



回答3:

I want to replace value in lista[index] with value from VAR -> variable.

From this, I think you're looking for something along these lines:

for index in (range(len(lista))):
    lista[index] = var

This changes all the items in the list to var.

If you don't want all items in the list to be replaced, you would need to make a decision to replace the correct item, and so maybe (if you already know the position of the item in the list that needs replacing):

lista[index] = var


回答4:

As kaasias wrote, just change the the elements of the list with this code:

for index in (range(len(lista))):
    lista[index] = var

and make sure you create your query with the new elements of the list.

query = "SELECT " + lista[0] + ", " + AdditionalInformation + ", " lista[1] + " FROM " + table