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
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.
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.
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.
split() only works with one argument, so I have all words with the punctuation after I split with whitespace.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With