It has a function instead of an operator, strings.Repeat
. Here's a port of your Python example, which you can run here:
package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func main() {
x := "my new text is this long"
y := strings.Repeat("#", utf8.RuneCountInString(x))
fmt.Println(x)
fmt.Println(y)
}
Note that I've used utf8.RuneCountInString(x)
instead of len(x)
; the former counts "runes" (Unicode code points), while the latter counts bytes. In the case of "my new text is this long"
, the difference doesn't matter since all the characters are only one byte, but it's good to get into the habit of specifying what you mean:
len("ā") //=> 2
utf8.RuneCountInString("ā") //=> 1
(In Python 2, len
counts bytes on plain strings and runes on Unicode strings (u'...'
):
>>> len('ā') #=> 2
>>> len(u'ā') #=> 1
In Python 3, plain strings are Unicode strings and len
counts runes; if you want to count bytes, you have to encode the string into a bytearray
first:
>>> len('ā') #=> 1
>>> len('ā'.encode('utf-8')) #=> 2
In Go, there's only one kind of string. So you don't have to convert, but you do have to pick the function that matches the semantics you want.)