Skip to content

py: implement str.join #240

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions py/string.go
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
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
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy