13

In Python if I do...:

parts = "".split(",")
print parts, len(parts)

The output is:

[], 0

If I do the equivalent in Go...:

parts = strings.Split("", ",")        
fmt.Println(parts, len(parts))

the output is:

[], 1

How can it have a length of 1 if there's nothing in it?

2
  • 2
    Demonstrated here play.golang.org/p/heJXcjerIN Commented Feb 4, 2015 at 20:34
  • Oh my, I just learned that its length is 1 in C++ too. For all these years I didn't know that. But why didn't I? Commented Feb 4, 2015 at 22:37

3 Answers 3

14

The result of strings.Split is a slice with one element - the empty string.

fmt.Println is just not displaying it. Try this example (notice the change to the last print).

package main

import "fmt"
import "strings"

func main() {
    groups := strings.Split("one,two", ",")
    fmt.Println(groups, len(groups))
    groups = strings.Split("one", ",")
    fmt.Println(groups, len(groups))
    groups = strings.Split("", ",")
    fmt.Printf("%q, %d\n", groups, len(groups))
}

Playground link

This makes sense. If you wanted to split the string "HelloWorld" using a , character as the delimiter, you'd expect the result to be "HelloWorld" - the same as your input.

Sign up to request clarification or add additional context in comments.

1 Comment

I noticed that it's actually the same in JavaScript. ("".split(',')).length is 1.
3

You can only get that result if both strings are empty:

package main

import (
   "fmt"
   "strings"
)

func main() {
   parts := strings.Split("", "")
   fmt.Println(parts, len(parts)) // [] 0
}

Which is documented:

If both s and sep are empty, Split returns an empty slice.

https://golang.org/pkg/strings#Split

Comments

3

If you're used to Python's behaviour in str.split, you'll find a tiny wrapper around strings.Split helpful.

func realySplit(s, sep string) []string {
    if len(s) == 0 {
        return []string{}
    }
    return strings.Split(s, sep)
}

1 Comment

Can simplify it to return nil instead of return []string{}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.