FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

py: implement str.join by aisk · Pull Request #240 · go-python/gpython · GitHub

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .go  (1) .py  (1) All 2 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
27 changes: 27 additions & 0 deletions py/string.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,9 @@ replaced.`)
return self.(String).Lower()
}, 0, "lower() -> a copy of the string converted to lowercase")

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

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

func (s String) Join(args Tuple) (Object, error) {
if len(args) != 1 {
return nil, ExceptionNewf(TypeError, "join() takes exactly one argument (%d given)", len(args))
}
var parts []string
iterable, err := Iter(args[0])
if err != nil {
return nil, err
}
item, err := Next(iterable)
for err == nil {
str, ok := item.(String)
if !ok {
return nil, ExceptionNewf(TypeError, "sequence item %d: expected str instance, %s found", len(parts), item.Type().Name)
}
parts = append(parts, string(str))
item, err = Next(iterable)
}
if err != StopIteration {
return nil, err
}
return String(strings.Join(parts, string(s))), nil
}

// Check stringerface is satisfied
var (
_ richComparison = String("")
Expand Down
9 changes: 9 additions & 0 deletions py/tests/string.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,15 @@ def index(s, i):
a = "ABC"
assert a.lower() == "abc"

doc="join"
assert ",".join(['a', 'b', 'c']) == "a,b,c"
assert " ".join(('a', 'b', 'c')) == "a b c"
assert " ".join("abc") == "a b c"
assert "".join(['a', 'b', 'c']) == "abc"
assert ",".join([]) == ""
assert ",".join(()) == ""
assertRaises(TypeError, lambda: ",".join([1, 2, 3]))

class Index:
def __index__(self):
return 1
Expand Down

Back | FazBrowse Home | New Git URL