Commit f7ed69df authored by Kevin Modzelewski's avatar Kevin Modzelewski

Merge pull request #327 from undingen/str_translate

Implement str.translate() with delete chars
parents 376e8e77 4a487488
...@@ -1695,21 +1695,31 @@ Box* strTitle(BoxedString* self) { ...@@ -1695,21 +1695,31 @@ Box* strTitle(BoxedString* self) {
} }
Box* strTranslate(BoxedString* self, BoxedString* table, BoxedString* delete_chars) { Box* strTranslate(BoxedString* self, BoxedString* table, BoxedString* delete_chars) {
RELEASE_ASSERT(self->cls == str_cls, ""); if (self->cls != str_cls)
RELEASE_ASSERT(table->cls == str_cls, ""); raiseExcHelper(TypeError, "descriptor 'translate' requires a 'str' object but received a '%s'",
RELEASE_ASSERT(delete_chars == NULL || delete_chars->cls == str_cls, ""); getTypeName(self));
RELEASE_ASSERT(delete_chars == NULL || delete_chars->s.size() == 0, "delete_chars not supported yet");
std::ostringstream oss; std::unordered_set<char> delete_set;
if (delete_chars) {
if (delete_chars->cls != str_cls)
raiseExcHelper(TypeError, "expected a character buffer object");
delete_set.insert(delete_chars->s.begin(), delete_chars->s.end());
}
if (table->s.size() != 256) bool have_table = table != None;
raiseExcHelper(ValueError, "translation table must be 256 characters long"); if (have_table) {
if (table->cls != str_cls)
raiseExcHelper(TypeError, "expected a character buffer object");
if (table->s.size() != 256)
raiseExcHelper(ValueError, "translation table must be 256 characters long");
}
for (unsigned char c : self->s) { std::string str;
oss << table->s[c]; for (const char c : self->s) {
if (!delete_set.count(c))
str.append(1, have_table ? table->s[(unsigned char)c] : c);
} }
return boxString(oss.str()); return boxString(std::move(str));
} }
Box* strLower(BoxedString* self) { Box* strLower(BoxedString* self) {
......
...@@ -70,6 +70,8 @@ for c in "aeiou": ...@@ -70,6 +70,8 @@ for c in "aeiou":
translation_map = ''.join(translation_map) translation_map = ''.join(translation_map)
print "hello world".translate(translation_map) print "hello world".translate(translation_map)
print "hello world".translate(translation_map, "") print "hello world".translate(translation_map, "")
print "hello world".translate(translation_map, "llo")
print "hello world".translate(None, "llo")
for i in xrange(-10, 10): for i in xrange(-10, 10):
print i, "aaaaa".find("a", i) print i, "aaaaa".find("a", i)
......
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