Skip to content

Commit a0c0529

Browse files
authored
py: implement str.join
Fixes #232
1 parent 79bb925 commit a0c0529

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

py/string.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,9 @@ replaced.`)
226226
return self.(String).Lower()
227227
}, 0, "lower() -> a copy of the string converted to lowercase")
228228

229+
StringType.Dict["join"] = MustNewMethod("join", func(self Object, args Tuple) (Object, error) {
230+
return self.(String).Join(args)
231+
}, 0, "join(iterable) -> return a string which is the concatenation of the strings in iterable")
229232
}
230233

231234
// Type of this object
@@ -755,6 +758,30 @@ func (s String) Lower() (Object, error) {
755758
return String(strings.ToLower(string(s))), nil
756759
}
757760

761+
func (s String) Join(args Tuple) (Object, error) {
762+
if len(args) != 1 {
763+
return nil, ExceptionNewf(TypeError, "join() takes exactly one argument (%d given)", len(args))
764+
}
765+
var parts []string
766+
iterable, err := Iter(args[0])
767+
if err != nil {
768+
return nil, err
769+
}
770+
item, err := Next(iterable)
771+
for err == nil {
772+
str, ok := item.(String)
773+
if !ok {
774+
return nil, ExceptionNewf(TypeError, "sequence item %d: expected str instance, %s found", len(parts), item.Type().Name)
775+
}
776+
parts = append(parts, string(str))
777+
item, err = Next(iterable)
778+
}
779+
if err != StopIteration {
780+
return nil, err
781+
}
782+
return String(strings.Join(parts, string(s))), nil
783+
}
784+
758785
// Check stringerface is satisfied
759786
var (
760787
_ richComparison = String("")

py/tests/string.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -905,6 +905,15 @@ def index(s, i):
905905
a = "ABC"
906906
assert a.lower() == "abc"
907907

908+
doc="join"
909+
assert ",".join(['a', 'b', 'c']) == "a,b,c"
910+
assert " ".join(('a', 'b', 'c')) == "a b c"
911+
assert " ".join("abc") == "a b c"
912+
assert "".join(['a', 'b', 'c']) == "abc"
913+
assert ",".join([]) == ""
914+
assert ",".join(()) == ""
915+
assertRaises(TypeError, lambda: ",".join([1, 2, 3]))
916+
908917
class Index:
909918
def __index__(self):
910919
return 1

0 commit comments

Comments
 (0)