简体   繁体   English

替换整个单词Python(仅变量)

[英]Replace whole word Python (only variable)

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. 我正在尝试编写仅替换字符串变量中整个单词的代码。首先我找到了re.sub解决方案,但里面没有提到变量。 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 . 如上例所示,我想用lista[index] VAR -> variable值替换lista[index]中的值。

EDIT: 编辑:

Example query: 查询示例:

Select Information,AdditionalInformation,Price from Table

example lista vales: 列表清单示例:

Information, Price 

example var: 范例var:

var = "hide"

Finally query should looks: 最后查询应如下所示:

Select hide,AdditionalInformation,hide from Table

I think this should work: 我认为这应该工作:

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

You can compile a regex that matches any of the words in lista . 您可以编译与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; \\b用于匹配单词边界; this prevents "AdditionalInformation" from being modified. 这样可以防止“ AdditionalInformation”被修改。 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. 我们需要将其写为原始字符串r'\\b' ,否则它将被解释为退格的ANSI转义代码。

I want to replace value in lista[index] with value from VAR -> variable. 我想将lista [index]中的值替换为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 . 这会将列表中的所有项目更改为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

As kaasias wrote, just change the the elements of the list with this code: 正如kaasias所写,只需使用以下代码更改列表的元素:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM