有没有办法使用python string.format,这样当索引丢失时不会抛出异常,而是插入一个空字符串.
result = "i am an {error} example string {error2}".format(hello=2,error2="success")
Run Code Online (Sandbox Code Playgroud)
在这里,结果应该是:
"i am an example string success"
Run Code Online (Sandbox Code Playgroud)
现在,python抛出了一个keyerror并停止格式化.是否有可能改变这种行为?
谢谢
编辑:
存在Template.safe_substitute(即使使模式保持原样而不是插入空字符串),但对于string.format可能没有类似的东西
期望的行为类似于php中的字符串替换.
class Formatter(string.Formatter):
def get_value(self,key,args,kwargs):
try:
if hasattr(key,"__mod__"):
return args[key]
else:
return kwargs[key]
except:
return ""
Run Code Online (Sandbox Code Playgroud)
这似乎提供了期望的行为.
我正在尝试使用boost-mpl在编译时连接字符串但是从gcc获得错误.这是样本 -
using namespace boost;
using namespace std;
template<class A>
struct type {};
template<>
struct type<int> {
typedef mpl::string < 'i' > value;
};
template<>
struct type<char> {
typedef mpl::string < 'c' > value;
};
struct empty {
};
template<class A, class B, class C, class D>
struct converter;
template<class A, class B = empty, class C = empty, class D = empty>
struct converter {
typedef mpl::push_back< type<A>::value, converter<B,C,D>::value >::type value ;
};
template<>
struct converter<empty, empty, empty, empty> …Run Code Online (Sandbox Code Playgroud) 根据文档,只有在所有页面元素完成加载后才应发出loadFinished.这应该意味着它只会被调用一次,但是我注意到在像youtube.com这样的网站上,它会被调用两次?有没有其他方法来解决这个错误或什么是最可靠的方法来检测page.load事件?
这是测试代码:
import sys
from PyQt4 import QtCore, QtGui, QtWebKit
from PyQt4.QtCore import QUrl
from PyQt4.QtGui import QApplication
def onDone(val):
print "Done ...",val
def onStart():
print "Started..."
app = QApplication(sys.argv)
ui = QtWebKit.QWebView()
ui.loadStarted.connect(onStart)
ui.loadFinished.connect(onDone)
ui.load(QUrl("http://www.youtube.com"))
ui.showMaximized()
sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)
输出:
Started...
Done ... True
Started...
Done ... True
Run Code Online (Sandbox Code Playgroud)
编辑:有一个几乎相同的问题,但它> 2岁,仍然没有答案.
我已经使用java编译器树api为java源文件生成ast.但是,我无法访问源文件中的注释.
到目前为止,我一直无法找到从源文件中提取注释的方法..有没有办法使用编译器api或其他工具?
using namespace std;
float test1(float i){
return i * i;
}
int test2(int i){
return i+9;
}
struct Wrapper{
typedef void (*wrapper_type)(int);
template<class R, class A>
void wrap(string name,R (*fn) (A) ){
wrapper_type f_ = &Wrapper::wrapper1<R,A,fn>;
// in the real program, f_ would be passed in an array to some c library
wrappers[name] = f_;
}
void run(int i){
map<string,wrapper_type>::iterator it, end = wrappers.end();
for(it=wrappers.begin();it!=end;it++){
wrapper_type wt = (*it).second;
(*wt)(i);
}
}
template<class R, class A, R (*fn) (A)>
static …Run Code Online (Sandbox Code Playgroud)