简体   繁体   English

如何使用 re 在变量中找到特定字符串并进行更改?

[英]How can I find a specific string in a variable using re and change it?

How can I find a specific string in a variable and change it with regular expressions For example如何在变量中找到特定字符串并使用正则表达式更改它例如

import re
Variable_To_Change = "This is Variable Number ^NUMBER^"

How can I use RE to find the word ^NUMBER^ and change the variable so that it doesn't say ^NUMBER^ but actual number like "This is Variable Number 1"如何使用 RE 查找单词 ^NUMBER^ 并更改变量,使其不显示 ^NUMBER^ 而是实际数字,例如“这是变量编号 1”

why would you use re for this... I dont know but here you go你为什么要用re来做这个......我不知道,但你在这里

 re.sub("\^NUMBER\^","1",my_string)

you could just use你可以用

 my_string.replace("^NUMBER^",1)

Im now going to make some assumtions我现在要做一些假设

you have a data structure like follows你有一个如下的数据结构

data = {"NUMBER":1,"STRING":"hello friend","BOOL":True}

and you have a string as follows你有一个字符串如下

my_string = "I have ^NUMBER^ of apples to share with ^STRING^ and this is ^BOOL^"

and you want to substitute in the data from your data dictionary to the string并且您想将数据字典中的数据替换为字符串

this can be done with re or string.replace quite easily (If you would have better defined the original question I would have left this to begin with)这可以很容易地用restring.replace来完成(如果你能更好地定义原来的问题,我会从这里开始)

# with replace
for key,value in data.items():
    my_string = my_string.replace("^{key}^".format(key=key),str(value))
print(my_string)

# with RE
def match_found(match):
    return data.get(match.group(1),"???UNKNOWN VAR???")
my_string = re.sub("\^([A-Z]+)\^",match_found,my_string

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

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