How to slice one string in Go language into array of string letters it contains?
For example, turn string "abc" into array "a", "b", "c".
To convert a string to list of characters in Python, use the list() method to typecast the string into a list. The list() constructor builds a list directly from an iterable, and since the string is iterable, you can construct a list from it.
To convert a string in a list of words, you just need to split it on whitespace. You can use split() from the string class. The default delimiter for this method is whitespace, i.e., when called on a string, it'll split that string at whitespace characters.
Use the list() class to split a word into a list of letters, e.g. my_list = list(my_str) . The list() class will convert the string into a list of letters.
Use a conversion to runes, for example
package main import "fmt" func main() { s := "Hello, 世界" for i, r := range s { fmt.Printf("i%d r %c\n", i, r) } fmt.Println("----") a := []rune(s) for i, r := range a { fmt.Printf("i%d r %c\n", i, r) } }
Playground
Output:
i0 r H i1 r e i2 r l i3 r l i4 r o i5 r , i6 r i7 r 世 i10 r 界 ---- i0 r H i1 r e i2 r l i3 r l i4 r o i5 r , i6 r i7 r 世 i8 r 界
From the link:
Converting a value of a string type to a slice of runes type yields a slice containing the individual Unicode code points of the string. If the string is empty, the result is []rune(nil).
Use strings.Split on it:
package main import ( "fmt" "strings" ) func main() { fmt.Printf("%#v\n",strings.Split("abc", "")) }
http://play.golang.org/p/1tNfu0iyHS
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