Commit 2fa59346 authored by Kevin Modzelewski's avatar Kevin Modzelewski

Add str.translate()

parent 3e4b760a
......@@ -754,6 +754,22 @@ Box* strTitle(BoxedString* self) {
return boxString(s);
}
// TODO implement "deletechars". can also pass deletechars or None for 'table'
Box* strTranslate(BoxedString* self, BoxedString* table) {
RELEASE_ASSERT(self->cls == str_cls, "");
RELEASE_ASSERT(table->cls == str_cls, "");
std::ostringstream oss;
if (table->s.size() != 256)
raiseExcHelper(ValueError, "translation table must be 256 characters long");
for (unsigned char c : self->s) {
oss << table->s[c];
}
return boxString(oss.str());
}
Box* strLower(BoxedString* self) {
assert(self->cls == str_cls);
return boxString(llvm::StringRef(self->s).lower());
......@@ -1055,6 +1071,8 @@ void setupStr() {
str_cls->giveAttr("capitalize", new BoxedFunction(boxRTFunction((void*)strCapitalize, STR, 1)));
str_cls->giveAttr("title", new BoxedFunction(boxRTFunction((void*)strTitle, STR, 1)));
str_cls->giveAttr("translate", new BoxedFunction(boxRTFunction((void*)strTranslate, STR, 2)));
str_cls->giveAttr("__contains__", new BoxedFunction(boxRTFunction((void*)strContains, BOXED_BOOL, 2)));
str_cls->giveAttr("startswith", new BoxedFunction(boxRTFunction((void*)strStartswith, BOXED_BOOL, 2)));
......
......@@ -62,3 +62,9 @@ for i in ["", "a", "ab", "aa"]:
print i, j, i.startswith(j), j.startswith(i), i.endswith(j), j.endswith(i), i.find(j), j.find(i), i.rfind(j), j.rfind(i)
print "bananananananas".replace("anan", "an")
translation_map = [chr(c) for c in xrange(256)]
for c in "aeiou":
translation_map[ord(c)] = c.upper()
translation_map = ''.join(translation_map)
print "hello world".translate(translation_map)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment