Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get python-like split() working with go's strings.Split() [duplicate]

Tags:

split

go

In python, the split() function with no separator splits the on whitespace/tab etc. and returns a list with all spaces removed

>>> "string    with multiple      spaces".split()
['string', 'with', 'multiple', 'spaces']

How can I achieve something similar in go?

package main

import "fmt"
import "strings"

func main() {
    s := "string    with multiple      spaces"
    lst := strings.Split(s, " ")
    for k, v := range lst {
        fmt.Println(k,v)
    }
}

The above gives

0 string
1 
2 
3 
4 with
5 multiple
6 
7 
8 
9 
10 
11 spaces

I'd like to save each of the strings in lst[0], lst[1], lst[2] and lst[3]. Can this be done? Thanks

like image 895
linuxfan Avatar asked May 13 '15 17:05

linuxfan


People also ask

Does split work on strings Python?

Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you split a string and keep the separator in Python?

Method 1: Using '(\W)'() is used to keep or store the separators/delimiters along with the word characters. \W is a special sequence that returns a match where it does not find any word characters in the given string. Here it is used to find the delimiters while splitting the string.

How do you split multiple strings in Python?

Method 1: Split multiple characters from string using re. split() This is the most efficient and commonly used method to split multiple characters at once. It makes use of regex(regular expressions) in order to do this.

Can split () take multiple arguments?

split() only works with one argument, so I have all words with the punctuation after I split with whitespace.


1 Answers

You are looking for strings.Fields:

func Fields(s string) []string

Fields splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning an array of substrings of s or an empty list if s contains only white space.

Example

fmt.Printf("Fields are: %q", strings.Fields("  foo bar  baz   "))

Output:

Fields are: ["foo" "bar" "baz"]
like image 178
Tim Cooper Avatar answered Sep 19 '22 10:09

Tim Cooper