它有一个函数而不是一个运算符,strings.Repeat。这是您的 Python 示例的一个端口,您可以运行 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)
}
请注意,我使用的是utf8.RuneCountInString(x) 而不是len(x);前者计算“符文”(Unicode 代码点),而后者计算字节。在"my new text is this long" 的情况下,区别并不重要,因为所有字符都只有一个字节,但最好养成指定含义的习惯:
len("ā") //=> 2
utf8.RuneCountInString("ā") //=> 1
由于这是一个 Python 比较问题,请注意,在 Python 中,len 的一个函数会根据您调用它的方式计算不同的事物。在 Python 2 中,它计算纯字符串上的字节数和 Unicode 字符串上的符文 (u'...'):
Python 2.7.18 (default, Aug 15 2020, 17:03:20)
>>> len('ā') #=> 2
>>> len(u'ā') #=> 1
而在现代 Python 中,纯字符串是 Unicode 字符串:
Python 3.9.6 (default, Jun 29 2021, 19:36:19)
>>> len('ā') #=> 1
如果要统计字节数,需要先将字符串编码成bytearray:
>>> len('ā'.encode('UTF-8')) #=> 2
所以 Python 有多种类型的字符串和一个函数来获取它们的长度; Go 只有一种字符串,但你必须选择与你想要的语义相匹配的长度函数。