我想在Python中替换部分字符串。特别是,我想摆脱结构"Hello[hi, ... ,bye]"
,其中点代表任意长度的字符。
我发现在How to use string.replace() in python 3.x中解释了如何使用替换,但我无法弄清楚如何匹配模式"你好[hi,...,bye]"用任意一串字符代替' ...'
示例1:
text= "Hello.hi[. Hello[hi, my name is alice ,bye] ,bye]"
我想:result= "Hello.hi[., 123 my name is alice 456 ,bye]"
但我希望同样的模式也适用于例2:
text= "Hello.hi[., Hello[hi, have a good day ,bye] ,bye]"
我想:result= "Hello.hi[., 123 have a good day 456 ,bye]"
有什么建议吗?感谢。
答案 0 :(得分:0)
使用replace
。
text= "Hello[hi, my name is alice ,bye] "
text.replace('hi,', '123').replace(',bye', '456')
>>> 'Hello[123 my name is alice 456] '
同样适用于"你好[嗨,祝你有个美好的一天,再见]"
答案 1 :(得分:0)
试试这个,
public UserControl1()
{
InitializeComponent();
this.Loaded += (s, e) =>
{
if (this.DataContext == null)
{
MainWindow parentWindow = Window.GetWindow(this) as MainWindow;
if (parentWindow != null)
{
ParentViewModel parentViewModel = parentWindow.DataContext as ParentViewModel;
if (parentViewModel != null)
{
//set One or Two or do whatever you want to do here...
}
}
}
};
}
答案 2 :(得分:0)
解决方案
import re
text="Hello[hi, my name is alice ,bye]"
search = re.compile(r'Hello\[hi,(.*?),bye\]')
a=search.sub('123\\1 456', text)
print(a)